<?php
namespace app\controller;

use app\BaseController;
use think\facade\Db;
use think\Request;
use think\facade\View;
use app\validate\CheckClasses;
use think\exception\ValidateException;
use think\facade\Queue;
use EasyWeChat\Factory;


// 班级管理
class Classes extends BaseController
{


    public function index()
    {
        $course = Db::name('Course')
            ->where('status', '=', 1)
            ->field('courseid, e_seminar')
            ->select();
        View::assign('course', $course);

        return View::fetch();
    }



    public function load(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        $get = $request->get();
        $where = [];

        if (isset($get['status'])) {
            if (!empty($get['status'])) {
                if ($get['status'] == 1) {
                    $where[] = ['a.start', '>', time()];
                }elseif ($get['status'] == 2) {
                    $where[] = ['a.start', '<=', time()];
                    $where[] = ['a.end', '>=', time()];
                }elseif ($get['status'] == 3) {
                    $where[] = ['a.end', '<', time()];
                }
            }
        }


        if (isset($get['time'])) {
            if (!empty($get['time'])) {
                $t = explode(' - ', $get['time']);
                $where[] = ['a.start', 'between', [strtotime($t[0]), strtotime($t[1])+86399]];
            }
        }

        if (isset($get['time1'])) {
            if (!empty($get['time1'])) {
                $t1 = explode(' - ', $get['time1']);
                $where[] = ['a.end', 'between', [strtotime($t1[0]), strtotime($t1[1])+86399]];
            }
        }

        if (isset($get['keys'])) {
            if (!empty($get['keys'])) {
                $where[] = ['a.teacher_name|a.address|a.title|a.e_title|b.e_seminar', 'like', '%'.$get['keys'].'%'];
            }
        }

        if (isset($get['courseid'])) {
            if (!empty($get['courseid'])) {
                $where[] = ['a.courseid', '=', $get['courseid']];
            }
        }

        $where[] = ['a.status', 'in','1,2'];

        $total = Db::table('o_classes')
            ->alias('a')
            ->join('o_course b','a.courseid=b.courseid', 'left')
            ->where($where)
            ->count();

        $rows = Db::table('o_classes')
            ->alias('a')
            ->join('o_course b','a.courseid=b.courseid', 'left')
            ->where($where)
            ->field('a.id, a.courseid, a.start, a.end, a.status, b.e_seminar, a.title, a.open, a.scene')
            ->order('a.id', 'desc')
            ->page($get['page'], $get['limit'])
            ->select()
            ->toArray();

        foreach ($rows as &$v) {
            $v['time'] = date('Y-m-d H:i',$v['start']).' - '.date('Y-m-d H:i',$v['end']);

            if(empty($v['start']) && empty($v['end'])){
                $v['status_name'] = '<span>请设置开课时间</span>';
            }elseif ($v['start'] > time()) {
                $v['status_name'] = '<span style="color: #009688;">未开始</span>';
            }elseif(($v['start'] <= time()) && ($v['end'] >= time())) {
                $v['status_name'] = '<span style="color: #1E9FFF;">进行中</span>';
            }elseif($v['end'] < time()) {
                $v['status_name'] = '<span style="color: #FF5722;">已结束</span>';
            }
        }
        $data = array(
            'code'=> 0,
            'msg'=> '',
            'count' => $total,
            'data'=> $rows
        );
        return json($data);
    }

    public function export(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $id = $request->get('id');

        set_time_limit(0);
        //设置程序运行内存
        ini_set('memory_limit', '4096M');

        $fileName = '班级员工学习记录'.date('Ymd', time());
        header('Content-Encoding: UTF-8');
        header("Content-type:application/vnd.ms-excel;charset=UTF-8");
        header('Content-Disposition: attachment;filename="' . $fileName . '.csv"');


        //打开php标准输出流
        $fp = fopen('php://output', 'a');

        //添加BOM头，以UTF8编码导出CSV文件，如果文件头未添加BOM头，打开会出现乱码。
        fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));


        //添加导出标题
        fputcsv($fp, ['班级名称','课程名称','员工工号','员工姓名', 'Division', '部门', '注册方式','签到日期','签到时间','开始学习时间','学习时长(S)','学习时长(H)']);

        //链接数据库
        $total = Db::name('classes_user')
            ->alias('a')
            ->join('o_members b', 'b.userid=a.userid', 'left')
            ->join('o_course c', 'c.courseid=a.courseid', 'left')
            ->where('a.classes_id', '=', $id)
            ->where('b.status', '=', 1)
            ->count();

        $nums = 100; //每次导出数量
        $step = ceil($total/$nums); //循环次数

        for($i = 0; $i < $step; $i++) {
            $start = $i * $nums;

            $subQuery1 = Db::table('o_classes_log')
                ->field('SUM(learning_time) as time, userid')
                ->group('userid')
                ->buildSql();

            $rows = Db::name('classes_user')
                ->alias('a')
                ->join('o_members b', 'b.userid=a.userid', 'left')
                ->join('o_course c', 'c.courseid=a.courseid', 'left')
                ->join('o_classes d', 'd.id=a.classes_id', 'left')
                ->join($subQuery1.'e','e.userid=a.userid','left')
                ->where('a.classes_id', '=', $id)
                ->where('b.status', '=', 1)
                ->field('a.userid, a.classes_id, a.type, b.name, b.division, b.department_name, c.seminar, d.title, e.time')
                ->limit($start, $nums)
                ->select()
                ->toArray();

            foreach ($rows as $value) {
                $count = mb_strlen($value['userid']);
                if ($count == 6) {
                    if (is_numeric($value['userid'])) {
                        $carolid = "00".$value['userid'];
                    } else {
                        $carolid = $value['userid'];
                    }
                } else {
                    $carolid = $value['userid'];
                }

                $class_log = Db::name('classes_log')
                    ->where('userid', '=', $value['userid'])
                    ->where('classes_id', '=', $value['classes_id'])
                    ->order('add_time', 'asc')
                    ->find();
                $sign_log = Db::name('classes_log')
                    ->where('userid', '=', $value['userid'])
                    ->where('classes_id', '=', $value['classes_id'])
                    ->where('resource_id', '=', 0)
                    ->find();

                $arr = [
                    $value['title'],
                    $value['seminar'],
                    $carolid,
                    $value['name'],
                    $value['division'],
                    $value['department_name'],
                    $value['type'] == 1 ? '后台导入':'现场注册',
                    isset($sign_log['qiandao']) ? date('Y-m-d', $sign_log['add_time']) : '未签到',
                    isset($sign_log['qiandao']) ? date('H:i:s', $sign_log['add_time']) : '未签到',
                    (isset($class_log) ? date('Y-m-d H:i:s', $class_log['add_time']) : ''),
                    $value['time'],
                    number_format($value['time']/3600, 2)
                ];
                fputcsv($fp, $arr);
            }
            //每1千条数据就刷新缓冲区
            ob_flush();
            flush();
        }
    }

    // 导出
    public function exportAll(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }
        $post = $request->post();

        $res = Db::name('document')
            ->where('type', '=', 'ClassesTotalJobQueue')
            ->where('url', '=', '')
            ->find();

        if ($res) {
            return $this->outputAjax('已有下载任务, 请勿重复操作');
        }

        Db::startTrans();
        try {

            $ts = time();

            $insert = array(
                'admin_id' => session('admin_auth.id'),
                'title' => '所有班级学习明细-'.date('YmdHis', $ts),
                'url' => '',
                'type' => 'ClassesTotalJobQueue',
                'add_time' => $ts
            );

            $download_id = Db::name('document')->insertGetId($insert);
            if (!$download_id) {
                Db::rollback();
                return $this->outputAjax('任务添加失败[2]');
            }

            // 1.当前任务由哪个类来负责处理
            // 当轮到该任务时，系统将生成该类的实例，并调用其fire方法
            $jobHandlerClassName = 'app\job\JobClassesTotal@task1';

            // 2.当任务归属的队列名称，如果为新队列，会自动创建
            $jobQueueName = "ClassesTotalJobQueue";


            // 3.当前任务所需业务数据，不能为resource类型，其他类型最终将转化为json形式的字符串
            $jobData = ['ts' => $ts, 'download_id' => $download_id, 'page' => 1, 'time' => $post['time'], 'time1' => $post['time1'], 'status' => $post['status'], 'courseid' => $post['courseid'], 'keys' => $post['keys']];

            // 4.将该任务推送到消息列表，等待对应的消费者去执行
            // 入队列，later延迟执行，单位秒，push立即执行
            $isPushedTask1 = Queue::push($jobHandlerClassName, $jobData, $jobQueueName);

            // database 驱动时，返回值为 1|false  ;   redis 驱动时，返回值为 随机字符串|false
            if ($isPushedTask1 !== false) {

                Db::commit();
                return $this->outputAjax('任务添加成功, 稍后在下载中心查看', 0);

            } else {

                Db::rollback();
                return $this->outputAjax('任务添加失败');

            }
        } catch (\Exception $e) {

            Db::rollback();
            return $this->outputAjax($e->getMessage());

        }
    }


    // 分享二维码
    public function getQrCode(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $id = $request->param('id');

        try {

            $app = Factory::miniProgram($this->mini_config);

            $page = 'pages/training/pages/sign/index';
            $response = $app->app_code->getUnlimit($id, [
                'page'  => $page,
                'width' => 280,
            ]);

            $time = time();
            if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
                $filename = $response->saveAs(runtime_path().'/storage', $time.'.png');
            }

            $blob = new Upload();
            $res = $blob->uploadBlob(runtime_path().'/storage/'.$filename, $filename, 'image/png', 'small');
            if ($res['code'] == 200) {
                $qr = $res['data'];
            } else {
                $qr = '';
            }
            //删除文件
            unlink(runtime_path() . 'storage/' . $filename);
            return $this->outputAjax('获取成功', 0, ['url' => $qr]);

        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }


    public function downloadQrCode(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $id = $request->param('id');
        $title = $request->param('title');

        try {

            $app = Factory::miniProgram($this->mini_config);

            $page = 'pages/training/pages/sign/index';
            $response = $app->app_code->getUnlimit($id, [
                'page'  => $page,
                'width' => 1280,
            ]);

            $time = time();
            if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
                $filename = $response->saveAs(runtime_path().'/storage', $time.'.png');
            }

            $blob = new Upload();
            $res = $blob->uploadBlob(runtime_path().'/storage/'.$filename, $filename, 'image/png', 'small');
            if ($res['code'] == 200) {
                $qr = $res['data'];
            } else {
                $qr = '';
            }
            //删除文件
            unlink(runtime_path() . 'storage/' . $filename);

            $fileTmp = pathinfo($qr);
            $fileExt = $fileTmp['extension'];    //图片后缀名
            $filename = str_replace('.', '', $title);   //图片名称，可以任务设置图片名称
            $saveFileName = ($filename.'.'.$fileExt);
            $fp = fopen($qr,"r");
            //下载文件需要用到的头
            Header("Content-type: application/octet-stream");
            Header("Accept-Ranges: bytes");
            Header("Content-Disposition: attachment; filename=".$saveFileName);
            $buffer = 1024;
            $file_count = 0;
            //向浏览器返回数据
            while (!feof($fp)) {
                $file_con = fread($fp,$buffer);
                $file_count += $buffer;
                echo $file_con;
            }
            fclose($fp);
            exit;
        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }

    public function open(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $id = $request->post('id');
        if (!$id) {
            return $this->outputAjax();
        }
        try {
            $inf = Db::name('classes')->find($id);

            if (empty($inf)) {
                return $this->outputAjax('参数错误！');
            }

            if (!in_array($inf['open'], array(1, 2))) {
                return $this->outputAjax('参数错误[1]！');
            }

            $open = $inf['open'] == 1 ? 2 : 1;

            $update = array(
                'id' => $id,
                'open' => $open,
            );
            if(Db::name('classes')->update($update)) {
                return $this->outputAjax('操作成功！',0);
            }
            return $this->outputAjax('操作失败！');
        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }

    public function fabu(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $id = $request->post('id');
        if (!$id) {
            return $this->outputAjax();
        }

        try {

            $inf = Db::name('classes')->find($id);

            if (empty($inf)) {
                return $this->outputAjax('参数错误！');
            }

            if (!in_array($inf['status'], array(1, 2))) {
                return $this->outputAjax('参数错误[1]！');
            }

            $status = $inf['status'] == 1 ? 2 : 1;

            $update = array(
                'id' => $id,
                'status' => $status,
            );
            if(Db::name('classes')->update($update)) {
                return $this->outputAjax('操作成功！',0);
            }
            return $this->outputAjax('操作失败！');
        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }


    public function scene(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $id = $request->post('id');
        if (!$id) {
            return $this->outputAjax();
        }

        try {
            $inf = Db::name('Classes')->find($id);

            if (empty($inf)) {
                return $this->outputAjax('参数错误！');
            }

            if (!in_array($inf['scene'], array(1, 2))) {
                return $this->outputAjax('参数错误[1]！');
            }

            $scene = $inf['scene'] == 1 ? 2 : 1;

            $update = array(
                'id' => $id,
                'scene' => $scene,
            );
            if(Db::name('classes')->update($update)) {
                return $this->outputAjax('操作成功！',0);
            }
            return $this->outputAjax('操作失败！');
        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }

    public function delete(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $post = $request->post();

        $id = $post['id'];

        if (empty($id)) {
            return $this->outputAjax('请选择班级！');
        }
        try {
            $update = array(
                'id' => $id,
                'status' => 3,
            );
            if(Db::name('classes')->update($update)) {
                return $this->outputAjax('操作成功！',0);
            }

            return $this->outputAjax('删除成功！', 0);
        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }


    public function add()
    {
        if(!check_jurisdiction1(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        $teacher = Db::name('members')
            ->where('status', '=', 1)
            ->where('role', 'in', '2,3')
            ->field('id, userid, name')
            ->select();
        View::assign('teacher', $teacher);
        return View::fetch();
    }


    //+选择课程页
    public function showCourse()
    {
        return View::fetch();
    }

    //+课程信息获取
    public function getCourseList(Request $request)
    {
        $get = $request->get();
        $where = [];

        if (isset($get['keys'])) {
            if (!empty($get['keys'])) {
                $where[] = ['seminar|e_seminar|courseid', 'like', '%'.$get['keys'].'%'];
            }
        }

        $where[] = ['status', '=', 1];

        $total = Db::name('course')
            ->where($where)
            ->count();

        $rows = Db::name('course')
            ->where($where)
            ->field('id, courseid, seminar, e_seminar, module')
            ->order('add_time', 'desc')
            ->page($get['page'], $get['limit'])
            ->select()
            ->toArray();
        foreach ($rows as &$v) {
            $v['seminar'] = $v['seminar'] == '' ? $v['e_seminar']:$v['seminar'];
            $v['module_name'] = get_config('app.course.module', $v['module']);
            $v['seminar'] = str_replace('\'', '’', $v['seminar']);
        }
        $data = array(
            'code'=> 0,
            'msg'=> '',
            'count' => $total,
            'data'=> $rows
        );
        return json($data);
    }


    //+班级保存
    public function save(Request $request)
    {
        $post = $request->post();
        //$post = remove_xss($post);

        // 验证
        try {

            validate(CheckClasses::class)->check($post);

        } catch (ValidateException $e) {

            return $this->outputAjax($e->getError());
        }

        try {

            $name = Db::name('members')->where('id', 'in', $post['teacherid'])->column('name');
            $insert = array(
                'title'         => $post['title'],
                'e_title'       => $post['e_title'],
                'teacherid'     => $post['teacherid'],
                'teacher_name'  => implode('|', $name),
                'courseid'      => $post['courseid'],
                'start'         => strtotime($post['start']),
                'end'           => strtotime($post['end']),
                'address'       => $post['address'],
                'content'       => $post['content'],
                'scene'         => 1,
                'status'        => 2,
                'add_time'      => time(),
                'update_time'   => time(),
                'deadline'   => $post['deadline'] == '' ? 30 : $post['deadline'],
            );
            $class_id = Db::name('classes')->insertGetId($insert);
            if (!$class_id) {
                return $this->outputAjax('创建失败[1]！');
            }

            return $this->outputAjax('创建成功！', 0);
        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }


    public function edit(Request $request)
    {
        if(!check_jurisdiction1(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        $id = $request->get('id');

        $inf = Db::name('Classes')->find($id);
        $inf['course_name'] = Db::name('course')->where('courseid', '=', $inf['courseid'])->value('e_seminar');
        $inf['start'] = date('Y-m-d H:i:s', $inf['start']);
        $inf['end'] = date('Y-m-d H:i:s', $inf['end']);
        $inf['content'] = html_entity_decode($inf['content']);
        View::assign('inf',$inf);
        $teacher = Db::name('members')
            ->where('status', '=', 1)
            ->where('role', 'in', '2,3')
            ->where('id', 'not in', $inf['teacherid'])
            ->field('id, userid, name')
            ->select();
        View::assign('teacher', $teacher);
        $teacher1 = Db::name('members')
            ->where('status', '=', 1)
            ->where('role', 'in', '2,3')
            ->where('id', 'in', $inf['teacherid'])
            ->field('id, userid, name')
            ->select();
        View::assign('teacher1', $teacher1);
        return View::fetch();
    }

    public function modify(Request $request)
    {
        $post = $request->post();
        //$post = remove_xss($post);

        // 验证
        try {

            validate(CheckClasses::class)->check($post);

        } catch (ValidateException $e) {

            return $this->outputAjax($e->getError());
        }
        try {

            $name = Db::name('members')->where('id', 'in', $post['teacherid'])->column('name');
            $update = array(
                'id'            => $post['id'],
                'title'         => $post['title'],
                'e_title'       => $post['e_title'],
                'teacherid'     => $post['teacherid'],
                'teacher_name'  => implode('|', $name),
                'courseid'      => $post['courseid'],
                'start'         => strtotime($post['start']),
                'end'           => strtotime($post['end']),
                'address'       => $post['address'],
                'content'       => $post['content'],
                'update_time'   => time(),
                'deadline'   => $post['deadline'] == '' ? 30 : $post['deadline'],
            );
            if (!Db::name('classes')->update($update)) {
                return $this->outputAjax('保存失败[1]！');
            }
            return $this->outputAjax('保存成功！', 0);
        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }


    // 直播课学员
    public function members(Request $request)
    {
        $class_id = $request->get('id');
        View::assign('class_id', $class_id);
        return View::fetch();
    }


    public function getMembersList(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        $class_id = $request->get('class_id');
        $get = $request->get();

        $where = [];

        if (isset($get['keys'])) {
            if (!empty($get['keys'])) {
                $where[] = ['a.userid', 'like', '%'.$get['keys'].'%'];
            }
        }

        if (isset($get['sign_out'])) {
            if (!empty($get['sign_out'])) {
                $where[] = ['a.sign_out', '=', $get['sign_out']];
            }
        }

        if (isset($get['like'])) {
            if (!empty($get['like'])) {
                $where[] = ['a.like', '=', $get['like']];
            }
        }


        $where[] = ['a.classes_id', '=', $class_id];

        $total = Db::table('o_classes_user')
            ->alias('a')
            ->join('o_members b', 'b.userid=a.userid')
            ->where($where)
            ->count();

        $rows = Db::table('o_classes_user')
            ->alias('a')
            ->join('o_members b', 'b.userid=a.userid')
            ->field('a.*, b.name, b.department_name, b.division, b.mobile')
            ->where($where)
            ->page($get['page'], $get['limit'])
            ->select()
            ->toArray();

        foreach ($rows as &$v) {

            $f = Db::name('classes_log')
                ->where('classes_id', '=', $class_id)
                ->where('userid', '=', $v['userid'])
                ->where('qiandao', '=', 1)
                ->value('add_time');
            if ($f) {
                $v['qiandao'] = date('Y-m-d H:i',$f);
            } else {
                $v['qiandao'] = '未签到';
            }

            $count = mb_strlen($v['userid']);
            if ($count == 6) {
                if (is_numeric($v['userid'])) {
                    $v['userid'] = '00'.$v['userid'];
                } else {
                    $v['userid'] = $v['userid'];
                }
            } else {
                $v['userid'] = $v['userid'];
            }
            $v['mobile'] = decrypts($v['mobile']);
        }
        $data = array(
            'code'=> 0,
            'msg'=> '',
            'count' => $total,
            'data'=> $rows
        );
        return json($data);
    }


    public function exportMembers(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $get = $request->get();
        $class_id = $request->get('class_id');
        set_time_limit(0);
        //设置程序运行内存
        ini_set('memory_limit', '4096M');

        $fileName = '班级学员数据'.date('Ymd', time());
        header('Content-Encoding: UTF-8');
        header("Content-type:application/vnd.ms-excel;charset=UTF-8");
        header('Content-Disposition: attachment;filename="' . $fileName . '.csv"');


        //打开php标准输出流
        $fp = fopen('php://output', 'a');

        //添加BOM头，以UTF8编码导出CSV文件，如果文件头未添加BOM头，打开会出现乱码。
        fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));


        //添加导出标题
        fputcsv($fp, ['工号', '姓名', '手机号', 'Division', '部门', '注册类型', '已退出', '我的最爱', '签到']);

        $where = [];

        if (isset($get['keys'])) {
            if (!empty($get['keys'])) {
                $where[] = ['userid', 'like', '%'.$get['keys'].'%'];
            }
        }

        if (isset($get['sign_out'])) {
            if (!empty($get['sign_out'])) {
                $where[] = ['sign_out', '=', $get['sign_out']];
            }
        }

        if (isset($get['like'])) {
            if (!empty($get['like'])) {
                $where[] = ['like', '=', $get['like']];
            }
        }


        $where[] = ['classes_id', '=', $class_id];

        $total = Db::name('classes_user')
            ->where($where)
            ->count();

        $nums = 100; //每次导出数量
        $step = ceil($total/$nums); //循环次数

        for($i = 0; $i < $step; $i++) {
            $start = $i * $nums;
            $rows = Db::name('classes_user')
                ->where($where)
                ->limit($start, $nums)
                ->select()
                ->toArray();

            foreach ($rows as &$v) {

                $f = Db::name('classes_log')
                    ->where('classes_id', '=', $class_id)
                    ->where('userid', '=', $v['userid'])
                    ->where('qiandao', '=', 1)
                    ->value('add_time');
                if ($f) {
                    $qiandao = date('Y-m-d H:i',$f);
                } else {
                    $qiandao = '未签到';
                }

                $member = Db::name('members')
                    ->where('userid', '=', $v['userid'])
                    ->field('name, userid, department_name, division, mobile')
                    ->find();
                if ($member) {
                    $count = mb_strlen($member['userid']);
                    if ($count == 6) {
                        if (is_numeric($member['userid'])) {
                            $userid = "'00".$member['userid'];
                        } else {
                            $userid = $member['userid'];
                        }
                    } else {
                        $userid = $member['userid'];
                    }
                    $name = $member['name'];
                    $department_name = $member['department_name'];
                    $division = $member['division'];
                    $mobile = decrypts($member['mobile']);
                } else {
                    $name = '';
                    $department_name = '';
                    $division = '';
                    $mobile = '';
                }

                $arr = [
                    $userid,
                    $name,
                    $mobile,
                    $division,
                    $department_name,
                    $v['type'] == 1 ? '后台导入' : '现场注册',
                    $v['sign_out'] == 1 ? '否' : '是',
                    $v['like'] == 1 ? '否' : '是',
                    $qiandao,
                ];
                fputcsv($fp, $arr);
            }

            //每1千条数据就刷新缓冲区
            ob_flush();
            flush();
        }
    }

    public function deleteMembers(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $id = $request->param('id');

        if (!$id) {
            return $this->outputAjax('参数不足！');
        }

        $id = explode(',',trim($id,','));

        Db::startTrans();
        try {
            foreach ($id as $key => $value) {
                if (!Db::name('classes_user')->where('id', '=', $value)->delete()) {
                    Db::rollback();
                    return $this->outputAjax('删除失败[1]！');
                }
            }

            Db::commit();
            return $this->outputAjax('删除成功！', 0);
        } catch (\Exception $e) {
            Db::rollback();
            return $this->outputAjax($e->getMessage());
        }
    }

    public function user(Request $request)
    {
        $class_id = $request->param('class_id');
        View::assign('class_id', $class_id);
        return View::fetch();
    }

    public function saveUser(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $class_id = $request->post('class_id');
        $uid = $request->post('id');

        if(!$class_id){
            return $this->outputAjax('缺少班级id！');
        }

        try {
            $uids = explode(',',$uid);
            if(!is_array($uids) || count($uids) <= 0){
                return $this->outputAjax('请选择学员！');
            }


            $class = Db::name('classes')->find($class_id);

            $t = [];
            $t['classes_id'] = $class_id;
            $t['courseid'] = $class['courseid'];
            $t['add_time'] = time();

            foreach ($uids as $key => $value) {
                $user = Db::name('members')
                    ->where('id', '=', $value)
                    ->field('id, userid, name')
                    ->find();
                $res = Db::name('classes_user')
                    ->where('userid', '=', $user['userid'])
                    ->where('classes_id', '=', $class_id)
                    ->find();
                if($res){
                    continue;
                }
                $t['userid'] = $user['userid'];
                Db::name('classes_user')->insert($t);
            }
            return $this->outputAjax('添加成功！',0);
        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }


    //文件批量导入学员
    public function import(Request $request)
    {
        $class_id = $request->param('class_id');
        View::assign('class_id', $class_id);
        return View::fetch();
    }


    public function executeImport(Request $request)
    {
        if (!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限', 2);
        }

        set_time_limit(0);

        $filename = $request->param('path');

        $class_id = $request->param('class_id');

        if(empty($class_id)) {
            return $this->outputAjax('参数缺失', 2);
        }
        $class = Db::name('classes')->where('id', '=', $class_id)->find();
        if(!$class) {
            return $this->outputAjax('课程不存在', 2);
        }

        try {

            // 获取excel表格数据
            $result = get_excel_info($filename);
            if ($result['code'] == 1) {
                return $this->outputAjax($result['msg'], 2);
            }

            $i = 0;
            foreach ($result['data'] as $key => $value) {
                $userid = $value[0];

                $user = Db::name('members')
                    ->where('userid', '=', $userid)
                    ->field('id, userid, language, name')
                    ->find();
                if (!$user) {
                    continue;
                }

                $res = Db::name('classes_user')
                    ->where('userid', '=', $userid)
                    ->where('classes_id', '=', $class_id)
                    ->find();
                if($res) {
                    continue;
                }

                $newValue = [
                    'classes_id' => $class_id,
                    'courseid' => $class['courseid'],
                    'add_time' => time(),
                    'userid' => $userid,
                ];
                $f = Db::name('classes_user')->insert($newValue);
                if ($f) {
                    $i++;
                }
            }
            return $this->outputAjax('导入成功！', 0, [$i, count($result['data'])-$i]);
        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage(), 2);
        }
    }


    //培训安排
    public function step(Request $request)
    {
        $class_id = $request->get('class_id');

        if (!$class_id) {
            return $this->outputAjax('参数不足！');
        }

        $data = Db::name('classes_step')
            ->where('classes_id', '=', $class_id)
            ->order(['sort'=>'asc', 'add_time'=>'desc'])
            ->select()
            ->toArray();

        foreach ($data as &$v) {
            $resource = Db::name('classes_step_resource')
                ->alias('a')
                ->join('o_courseware b', 'a.courseware_id=b.id','left')
                ->field('a.id, a.classes_id, a.add_time, b.title, b.duration,b.type, b.id as courseware_id')
                ->where('a.classes_id', '=', $class_id)
                ->where('a.status', '=', 1)
                ->where('a.step_id', '=', $v['id'])
                ->order(['a.sort'=> 'asc','a.add_time'=> 'asc'])
                ->select()
                ->toArray();

            foreach ($resource as &$val) {
                $val['duration'] = $val['duration'] ? sprintf("%.2f", $val['duration']/60):'';
                if ($val['type'] == 1) {
                    $val['type_name'] = '<span style="color: #1E9FFF;">图文</span>';
                } elseif ($val['type'] == 2) {
                    $val['type_name'] = '<span style="color: #FFB800;">文档</span>';
                } elseif ($val['type'] == 3) {
                    $val['type_name'] = '<span style="color: #FF5722;">测试</span>';
                } elseif ($val['type'] == 4) {
                    $val['type_name'] = '<span style="color: #FF5722;">调研</span>';
                } elseif ($val['type'] == 5) {
                    $val['type_name'] = '<span style="color: #2D8CF0;">外链</span>';
                } else {
                    $val['type_name'] = '';
                }
                $val['add_time'] = date('Y-m-d H:i:s', $val['add_time']);

                $val['end_time'] = '';

                if ($val['type'] == 4) {
                    $end_time = Db::name('courseware_survey')->where('courseware_id', '=', $val['courseware_id'])->value('end_time');
                    $val['end_time'] = $end_time == ''? '':date('Y-m-d H:i:s', $end_time);
                }
            }
            $v['resource'] = $resource;
        }

        View::assign('classes_id', $class_id);
        View::assign('data', $data);
        return View::fetch();
    }


    //+新增学习单元
    public function saveUnit(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $post = $request->post();
        $post = remove_xss($post);

        try {
            $data = array(
                'classes_id' => $post['classes_id'],
                'name' => $post['unit'],
                'add_time' => time(),
            );

            if (!Db::name('classes_step')->insert($data)) {
                return $this->outputAjax('新增失败！');
            } else {
                return $this->outputAjax('新增成功！', 0);
            }
        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }

    }


    //+修改学习单元
    public function modifyUnit(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $post = $request->post();
        $post = remove_xss($post);

        try {
            $data = array(
                'id' => $post['id'],
                'name' => $post['unit'],
            );

            if (!Db::name('classes_step')->update($data)) {
                return $this->outputAjax('修改失败！');
            } else {
                return $this->outputAjax('修改成功！', 0);
            }
        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }

    }


    //+删除学习单元
    public function deleteUnit(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $id = $request->post('id');
        if (!$id) {
            return $this->outputAjax('非法参数！');
        }

        try {
            $res = Db::name('classes_step_resource')->where('step_id', '=', $id)->where('status', '=', 1)->find();
            if ($res) {
                return $this->outputAjax('该单元下有任务，无法删除！');
            }

            if (!Db::name('classes_step')->where('id', '=', $id)->delete()) {
                return $this->outputAjax('删除失败！');
            }

            return $this->outputAjax('删除成功！', 0);

        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }


    //+单元排序
    public function sortUnit(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $sortstr = $request->post('sortstr');

        if (empty($sortstr)) {
            return $this->outputAjax('参数不足！');
        }

        try {

            $sortarr = explode(',', $sortstr);

            foreach ($sortarr as $key => $val) {
                Db::name('classes_step')->where('id', '=', $val)->update(['sort' => $key+1]);
            }
            return $this->outputAjax('排序成功！', 0);

        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }


    // 选择课件
    public function courseware(Request $request)
    {
        $classes_id = $request->get('classes_id');
        $unit_id = $request->get('unit_id');
        $cate = Db::name('courseware_cate')->where('status', '=', 1)->field('id, title')->select();
        $label = Db::name('courseware_label')->where('status', '=', 1)->field('id, title')->select();

        View::assign('cate', $cate);
        View::assign('label', $label);
        View::assign('classes_id', $classes_id);
        View::assign('unit_id', $unit_id);

        return View::fetch();
    }



    public function saveCourseware(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $classes_id = $request->post('classes_id');
        $unit_id = $request->post('unit_id');
        $id = $request->post('id');

        if(!$classes_id) {
            return $this->outputAjax('缺少班级id！');
        }

        if(!$unit_id) {
            return $this->outputAjax('缺少单元id！');
        }

        Db::startTrans();
        try {

            $ids = explode(',',$id);
            if(!is_array($ids) || count($ids) <= 0){
                return $this->outputAjax('请选择课件！');
            }


            $t = [];
            $t['classes_id'] = $classes_id;
            $t['step_id'] = $unit_id;
            $t['status'] = 1;
            $t['add_time'] = time();

            foreach ($ids as $key => $value) {
                $t['courseware_id'] = $value;
                if (!Db::name('classes_step_resource')->insert($t)) {
                    Db::rollback();
                    return $this->outputAjax('添加失败！');
                }

                if (!Db::name('courseware')->where('id', '=', $value)->inc('num_of_add')->update()) {
                    Db::rollback();
                    return $this->outputAjax('添加失败[1]');
                }
            }
            Db::commit();
            return $this->outputAjax('添加成功！',0);
        } catch (\Exception $e) {
            Db::rollback();
            return $this->outputAjax($e->getMessage());
        }
    }

    /**
     * 课件排序
     * @date: 2019年3月27日
     * @author: Administrator
     * @return:
     */
    public function sortCourseware(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $classes_id = $request->post('classes_id');
        if (!$classes_id) {
            return json(['code'=>500,'msg'=>'缺少班级id']);
        }

        $sorts = $request->param('resource/a');

        try {
            if (is_array($sorts)) {
                foreach ($sorts as $key => $value){
                    Db::name('classes_step_resource')
                        ->where('id', '=', $value)
                        ->where('classes_id', '=', $classes_id)
                        ->update(['sort'=>$key]);
                }
                return json(['code'=>200,'msg'=>'排序成功']);
            } else {
                return json(['code'=>500,'msg'=>'缺少排序数据']);
            }
        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }


    // 删除课件
    public function deleteResource(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $classes_id = $request->post('classes_id');
        if (!$classes_id) {
            return json(['code'=>500,'msg'=>'缺少班级id']);
        }

        $id = $request->post('id');

        Db::startTrans();
        try {

            $res = Db::name('classes_step_resource')->where('id', '=', $id)->where('classes_id', '=', $classes_id)->find();

            if (!Db::name('classes_step_resource')->where('id', '=', $id)->where('classes_id', '=', $classes_id)->update(['status' => 3])) {
                Db::rollback();
                return $this->outputAjax('删除失败！');
            }

            if (!Db::name('courseware')->where('id', '=', $res['courseware_id'])->dec('num_of_add')->update()) {
                Db::rollback();
                return $this->outputAjax('删除失败[1]');
            }

            Db::commit();
            return $this->outputAjax('删除成功！', 0);

        } catch (\Exception $e) {
            Db::rollback();
            return $this->outputAjax($e->getMessage());
        }
    }

    // 课件学习记录
    public function log(Request $request)
    {
        $resource_id = $request->get('resource_id');
        $classes_id = $request->get('classes_id');

        View::assign('resource_id', $resource_id);
        View::assign('classes_id', $classes_id);
        return View::fetch();
    }

    // 课件学习记录加载
    public function getLogList(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        $get = $request->get();

        $where = [];

        if (isset($get['key'])) {
            if (!empty($get['key'])) {
                $where[] = ['b.name|b.userid', 'like', '%' . $get['key'] . '%'];
            }
        }

        $where[] = ['a.resource_id', '=', $get['resource_id']];
        $where[] = ['a.classes_id', '=', $get['classes_id']];

        $total = Db::table('o_classes_log')
            ->alias('a')
            ->join('o_members b', 'a.userid=b.userid', 'left')
            ->join('o_classes_step_resource c', 'c.id=a.resource_id', 'left')
            ->join('o_courseware d', 'd.id=c.courseware_id', 'left')
            ->where($where)
            ->count();

        $rows = Db::table('o_classes_log')
            ->alias('a')
            ->join('o_members b', 'a.userid=b.userid', 'left')
            ->join('o_classes_step_resource c', 'c.id=a.resource_id', 'left')
            ->join('o_courseware d', 'd.id=c.courseware_id', 'left')
            ->where($where)
            ->order('a.add_time', 'desc')
            ->field('a.id, d.title, a.name, b.department_name, b.division, a.userid, a.add_time, a.learning_time, a.source')
            ->page($get['page'], $get['limit'])
            ->select()
            ->toArray();

        foreach ($rows as &$v) {
            $v['add_time'] = date('Y-m-d H:i',$v['add_time']);
            $count = mb_strlen($v['userid']);
            if ($count == 6) {
                if (is_numeric($v['userid'])) {
                    $v['userid'] = '00'.$v['userid'];
                }
            }

            if ($v['source'] == 1) {
                $v['source_name'] = '小程序';
            } else {
                $v['source_name'] = 'PC端';
            }
        }

        $data = array(
            'code'=> 0,
            'msg'=> '',
            'count' => $total,
            'data'=> $rows
        );
        return json($data);
    }


    //+删除课件学习记录
    public function deleteLog(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $id = $request->post('id');

        if (!$id) {
            return $this->outputAjax('参数不足！');
        }

        try {

            if (!Db::name('classes_log')->where('id', '=', $id)->delete()) {
                return $this->outputAjax('删除失败！');
            }

            return $this->outputAjax('删除成功！', 0);

        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }


    // 导出课件学习记录
    public function exportLog(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        ob_end_clean ();
        set_time_limit(0);
        //设置程序运行内存
        ini_set('memory_limit', '4096M');

        $fileName = '课件学习明细'.date('Ymd', time());
        header('Content-Encoding: UTF-8');
        header("Content-type:application/vnd.ms-excel;charset=UTF-8");
        header('Content-Disposition: attachment;filename="' . $fileName . '.csv"');


        //打开php标准输出流
        $fp = fopen('php://output', 'a');

        //添加BOM头，以UTF8编码导出CSV文件，如果文件头未添加BOM头，打开会出现乱码。
        fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));


        //添加导出标题
        fputcsv($fp, ['工号', '姓名', 'Division', '部门', '课件名称', '开始学习时间', '学习时长(s)', '数据来源']);

        $get = $request->get();

        $where = [];

        if (!empty($get['key'])) {
            $where[] = ['b.name|b.userid', 'like', '%' . $get['keys'] . '%'];
        }

        $where[] = ['a.resource_id', '=', $get['resource_id']];
        $where[] = ['a.classes_id', '=', $get['classes_id']];


        // 取得满足条件的记录数

        $total = Db::table('o_classes_log')
            ->alias('a')
            ->join('o_members b', 'a.userid=b.userid', 'left')
            ->join('o_classes_step_resource c', 'c.id=a.resource_id', 'left')
            ->join('o_courseware d', 'd.id=c.courseware_id', 'left')
            ->where($where)
            ->count();

        $nums = 10; //每次导出数量
        $step = ceil($total/$nums); //循环次数

        for($i = 0; $i < $step; $i++) {
            $start = $i * $nums;

            // 分页查询数据
            $rows = Db::table('o_classes_log')
                ->alias('a')
                ->join('o_members b', 'a.userid=b.userid', 'left')
                ->join('o_classes_step_resource c', 'c.id=a.resource_id', 'left')
                ->join('o_courseware d', 'd.id=c.courseware_id', 'left')
                ->where($where)
                ->order('a.add_time', 'desc')
                ->field('a.id, d.title, a.name, b.department_name, b.division, a.userid, a.add_time, a.learning_time, a.source')
                ->limit($start, $nums)
                ->select()
                ->toArray();

            foreach ($rows as &$v) {

                $add_time = date('Y-m-d H:i',$v['add_time']);

                $count = mb_strlen($v['userid']);
                if ($count == 6) {
                    if (is_numeric($v['userid'])) {
                        $userid = "'00".$v['userid'];
                    } else {
                        $userid = $v['userid'];
                    }
                } else {
                    $userid = $v['userid'];
                }

                if ($v['source'] == 1) {
                    $source_name = '小程序';
                } else {
                    $source_name = 'PC端';
                }

                $arr = [
                    $userid,
                    $v['name'],
                    $v['division'],
                    $v['department_name'],
                    $v['title'],
                    $add_time,
                    $v['learning_time'],
                    $source_name
                ];

                fputcsv($fp, $arr);
            }

            flush();
        }
    }


    // 测试课件学习记录
    public function testLog(Request $request)
    {
        $resource_id = $request->get('resource_id');
        $classes_id = $request->get('classes_id');

        View::assign('resource_id', $resource_id);
        View::assign('classes_id', $classes_id);
        return View::fetch();
    }

    public function getTestLogList(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        $get = $request->get();
        $where = [];

        if (isset($get['key'])) {
            if (!empty($get['key'])) {
                $where[] = ['b.name|b.userid', 'like', '%' . $get['key'] . '%'];
            }
        }

        $where[] = ['a.resource_id', '=', $get['resource_id']];
        $where[] = ['a.classes_id', '=', $get['classes_id']];


        $total = Db::table('o_classes_log')
            ->alias('a')
            ->join('o_members b', 'a.userid=b.userid', 'left')
            ->join('o_classes_step_resource c', 'c.id=a.resource_id', 'left')
            ->join('o_courseware d', 'd.id=c.courseware_id', 'left')
            ->where($where)
            ->count();

        $rows = Db::table('o_classes_log')
            ->alias('a')
            ->join('o_members b', 'a.userid=b.userid', 'left')
            ->join('o_classes_step_resource c', 'c.id=a.resource_id', 'left')
            ->join('o_courseware d', 'd.id=c.courseware_id', 'left')
            ->where($where)
            ->order('a.add_time', 'desc')
            ->field('a.id, a.resource_id, d.title, d.id as courseware_id, b.name, b.department_name, b.division, a.userid, a.add_time, a.learning_time')
            ->page($get['page'], $get['limit'])
            ->select()
            ->toArray();


        foreach ($rows as &$v) {
            $v['add_time'] = date('Y-m-d H:i',$v['add_time']);

            $test = get_test_data($v['courseware_id'], $v['resource_id'], $v['userid'],'userid', 0);

            $v['max_score'] = $test['max_score'];
            $v['test_count'] = $test['test_count'];
            $v['pass'] = $test['pass'];
            $v['near_time'] = $test['near_time'];

            if (empty($v['near_time'])) {
                $v['near_time'] = '---------';
            } else {
                $v['near_time'] = date('Y-m-d H:i',$v['near_time']);
            }

            $count = mb_strlen($v['userid']);
            if ($count == 6) {
                if (is_numeric($v['userid'])) {
                    $v['userid'] = '00'.$v['userid'];
                }
            }

        }

        $data = array(
            'code'=> 0,
            'msg'=> '',
            'count' => $total,
            'data'=> $rows
        );
        return json($data);
    }


    public function deleteTestLog(Request $request)
    {
        $id = $request->post('id');
        $resource_id = $request->post('resource_id');
        $classes_id = $request->post('classes_id');

        if (!$id) {
            return $this->outputAjax('参数不足！');
        }

        Db::startTrans();
        try {

            $test = Db::name('classes_step_resource')
                ->alias('a')
                ->join('o_courseware_test b', 'b.courseware_id=a.courseware_id', 'left')
                ->where('a.id', '=', $resource_id)
                ->where('a.classes_id', '=', $classes_id)
                ->field('b.id as test_id')
                ->find();

            $userid = Db::name('classes_log')
                ->where('id', '=', $id)
                ->value('userid');
            $uid = Db::name('members')->where('userid', '=', $userid)->value('id');

            $answer = Db::name('test_answer')
                ->where('resource_id', '=', $resource_id)
                ->where('userid', '=', $uid)
                ->where('test_id', '=', $test['test_id'])
                ->where('type', '=', 0)
                ->select()
                ->toArray();

            if (empty($answer)) {
                return $this->outputAjax('删除失败所选学员未提交！');
            }

            $log = Db::name('classes_log')->where('id', '=', $id)->delete();
            if (!$log) {
                Db::rollback();
                return $this->outputAjax('删除失败[1]！');
            }


            $answer = Db::name('test_answer')
                ->where('resource_id', '=', $resource_id)
                ->where('userid', '=', $uid)
                ->where('test_id', '=', $test['test_id'])
                ->where('type', '=', 0)
                ->delete();
            if (!$answer) {
                Db::rollback();
                return $this->outputAjax('删除失败[2]！');
            }

            $submit = Db::name('test_submit')
                ->where('resource_id', '=', $resource_id)
                ->where('userid', '=', $uid)
                ->where('test_id', '=', $test['test_id'])
                ->where('type', '=', 0)
                ->delete();
            if (!$submit) {
                Db::rollback();
                return $this->outputAjax('删除失败[3]！');
            }

            Db::commit();
            return $this->outputAjax('删除成功！', 0);

        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }

    // 导出测试课件学习记录
    public function exportTestLog(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        ob_end_clean ();
        set_time_limit(0);
        //设置程序运行内存
        ini_set('memory_limit', '4096M');

        $fileName = '课件学习明细'.date('Ymd', time());
        header('Content-Encoding: UTF-8');
        header("Content-type:application/vnd.ms-excel;charset=UTF-8");
        header('Content-Disposition: attachment;filename="' . $fileName . '.csv"');


        //打开php标准输出流
        $fp = fopen('php://output', 'a');

        //添加BOM头，以UTF8编码导出CSV文件，如果文件头未添加BOM头，打开会出现乱码。
        fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));


        //添加导出标题
        fputcsv($fp, ['工号', '姓名', 'Division', '部门', '课件名称', '开始学习时间', '学习时长(s)', '成绩', '已考次数', '通过情况', '最近提交时间']);

        $get = $request->get();

        $where = [];

        if (!empty($get['key'])) {
            $where[] = ['b.name|b.userid', 'like', '%' . $get['keys'] . '%'];
        }

        $where[] = ['a.resource_id', '=', $get['resource_id']];
        $where[] = ['a.classes_id', '=', $get['classes_id']];

        $total = Db::table('o_classes_log')
            ->alias('a')
            ->join('o_members b', 'a.userid=b.userid', 'left')
            ->join('o_classes_step_resource c', 'c.id=a.resource_id', 'left')
            ->join('o_courseware d', 'd.id=c.courseware_id', 'left')
            ->where($where)
            ->count();

        $nums = 10; //每次导出数量
        $step = ceil($total/$nums); //循环次数

        for($i = 0; $i < $step; $i++) {
            $start = $i * $nums;

            $rows = Db::table('o_classes_log')
                ->alias('a')
                ->join('o_members b', 'a.userid=b.userid', 'left')
                ->join('o_classes_step_resource c', 'c.id=a.resource_id', 'left')
                ->join('o_courseware d', 'd.id=c.courseware_id', 'left')
                ->where($where)
                ->order('a.add_time', 'desc')
                ->field('a.id, a.resource_id, d.title, d.id as courseware_id, b.name, b.department_name, b.division, a.userid, a.add_time, a.learning_time')
                ->limit($start, $nums)
                ->select()
                ->toArray();


            foreach ($rows as &$v) {
                $add_time = date('Y-m-d H:i',$v['add_time']);

                $test = get_test_data($v['courseware_id'], $v['resource_id'], $v['userid'],'userid', 0);


                if (empty($test['near_time'])) {
                    $near_time = '---------';
                } else {
                    $near_time = date('Y-m-d H:i', $test['near_time']);
                }

                $count = mb_strlen($v['userid']);
                if ($count == 6) {
                    if (is_numeric($v['userid'])) {
                        $userid = "'00".$v['userid'];
                    } else {
                        $userid = $v['userid'];
                    }
                } else {
                    $userid = $v['userid'];
                }

                $arr = [
                    $userid,
                    $v['name'],
                    $v['division'],
                    $v['department_name'],
                    $v['title'],
                    $add_time,
                    $v['learning_time'],
                    $test['max_score'],
                    $test['test_count'],
                    $test['pass'],
                    $near_time
                ];

                fputcsv($fp, $arr);
            }

            flush();
        }
    }


    // 导出测试课件答题记录()
    public function exportTestAnswerLog(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        ob_end_clean ();
        set_time_limit(0);
        //设置程序运行内存
        ini_set('memory_limit', '4096M');

        $fileName = '课件答题记录'.date('Ymd', time());
        header('Content-Encoding: UTF-8');
        header("Content-type:application/vnd.ms-excel;charset=UTF-8");
        header('Content-Disposition: attachment;filename="' . $fileName . '.csv"');


        //打开php标准输出流
        $fp = fopen('php://output', 'a');

        //添加BOM头，以UTF8编码导出CSV文件，如果文件头未添加BOM头，打开会出现乱码。
        fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));


        //添加导出标题
        fputcsv($fp, ['工号', '姓名', 'Division', '部门', '测试标题', '题目', '答案', '正确答案']);

        $get = $request->get();


        if (!empty($get['key'])) {
            $where[] = ['b.name|b.userid', 'like', '%' . $get['keys'] . '%'];
        }

        $where[] = ['a.resource_id', '=', $get['resource_id']];
        $where[] = ['a.submit_id', '>', 0];
        $where[] = ['a.type', '=', 0];


        $total = Db::table('o_test_answer')
            ->alias('a')
            ->join('o_members b','b.id=a.userid', 'left')
            ->join('o_courseware_test_question c','c.id=a.question_id', 'left')
            ->join('o_courseware_test d','d.id=a.test_id', 'left')
            ->where($where)
            ->count();

        $nums = 10; //每次导出数量
        $step = ceil($total/$nums); //循环次数

        for($i = 0; $i < $step; $i++) {
            $start = $i * $nums;

            $rows = Db::table('o_test_answer')
                ->alias('a')
                ->join('o_members b','b.id=a.userid', 'left')
                ->join('o_courseware_test_question c','c.id=a.question_id', 'left')
                ->join('o_courseware_test d','d.id=a.test_id', 'left')
                ->where($where)
                ->field('a.answer, b.userid, b.name, b.division, b.department_name, c.title as question_title, c.check, d.title')
                ->limit($start, $nums)
                ->select()
                ->toArray();

            foreach ($rows as &$v) {

                $count = mb_strlen($v['userid']);
                if ($count == 6) {
                    if (is_numeric($v['userid'])) {
                        $userid = '00'.$v['userid'];
                    } else {
                        $userid = $v['userid'];
                    }
                } else {
                    $userid = $v['userid'];
                }

                $arr = [
                    $userid,
                    $v['name'],
                    $v['division'],
                    $v['department_name'],
                    $v['title'],
                    $v['question_title'],
                    $v['answer'],
                    $v['check'],
                ];

                fputcsv($fp, $arr);
            }

            flush();
        }

    }


    /*
    测试课件学习记录排行榜
    */
    public function studyTop(Request $request)
    {

        $resource_id = $request->get('resource_id');

        $test_id = Db::name('test_answer')
            ->where('resource_id', '=', $resource_id)
            ->where('type', '=', 0)
            ->value('test_id');

        $list = get_test_rank($test_id, $resource_id, 0);

        foreach ($list as $key => $value) {
            $members = Db::name('members')->where('id', '=', $value['userid'])->field('name, head')->find();
            $list[$key]['members'] = $members;
        }

        View::assign('list', $list);
        return View::fetch();
    }

    /*
        测试课件数据分析
    */
    public function studyAnalyze(Request $request)
    {
        $resource_id = $request->get('resource_id');

        $classes_id = $request->get('classes_id');


        $class_user_userid = Db::name('classes_user')->where('classes_id', '=', $classes_id)->column('userid');

        $test_id = Db::name('test_answer')
            ->where('resource_id', '=', $resource_id)
            ->where('type', '=', 0)
            ->value('test_id');
        $test = Db::name('courseware_test')->where('id', '=', $test_id)->find();

        $list = Db::name('courseware_test_question')
            ->where('test_id', '=', $test_id)
            ->select()
            ->toArray();

        foreach ($list as $key => $value) {
            //一答人数 未答人数        每个答案的选择率    正确答案的正确率
            $value['answer'] = json_decode($value['answer'],true);
            $check_apr = 0; //单选答案的正确率
            //哥各个答案的选择率
            foreach ($value['answer']  as $k => $v) {
                $value['answer'][$k]['choose'] = 0;

                if ($value['a_type'] == 0) {
                    $count = Db::name('test_answer')
                        ->where('question_id', '=', $value['id'])
                        ->where('resource_id', '=', $resource_id)
                        ->where('submit_id', '>', 0)
                        ->where('type', '=', 0)
                        ->count();
                    $choose = Db::name('test_answer')
                        ->where('resource_id', '=', $resource_id)
                        ->where('answer', '=',$v['b'])
                        ->where('question_id', '=', $value['id'])
                        ->where('submit_id', '>', 0)
                        ->where('type', '=', 0)
                        ->count();
                    $value['answer'][$k]['choose'] = $choose == 0 ? 0:$choose/$count;

                    if ($value['check'] == $v['b']) {
                        $check_apr = $value['answer'][$k]['choose'];
                    }

                } else {
                    $arr = Db::name('test_answer')
                        ->where('resource_id', '=', $resource_id)
                        ->where('question_id', '=', $value['id'])
                        ->where('submit_id', '>', 0)
                        ->where('type', '=', 0)
                        ->column('answer');
                    $arr = implode(',',$arr);
                    $arr = explode(',', $arr);
                    $count = count($arr);
                    $arr_count = array_count_values($arr);
                    $value['answer'][$k]['choose'] = isset($arr_count[$v['b']]) ? $arr_count[$v['b']]/$count:0;
                }

                $value['answer'][$k]['choose'] = sprintf("%.2f", $value['answer'][$k]['choose'] * 100).'%';
            }

            //正确答案的正确率
            if ($value['a_type'] == 0) {
                $value['check_apr'] = $check_apr;

            } else {

                $arr = Db::name('test_answer')
                    ->where('resource_id', '=', $resource_id)
                    ->where('question_id', '=', $value['id'])
                    ->where('submit_id', '>', 0)
                    ->where('type', '=', 0)
                    ->select()
                    ->toArray();

                $count = count($arr);
                $arr_count = 0;
                foreach ($arr as $k => $v) {
                    $a1 = explode(',',$value['check']);
                    $a2 = explode(',',$v['answer']);
                    if($a1 == $a2){
                        $arr_count++;
                    }
                }
                $value['check_apr'] = $arr_count == 0 ? 0: $arr_count/$count;
            }

            $value['check_apr'] = sprintf("%.2f", $value['check_apr'] * 100).'%';
            //计算人数
            $answer_count = Db::name('test_answer')
                ->field('id')
                ->where('resource_id', '=', $resource_id)
                ->where('question_id', '=', $value['id'])
                ->where('submit_id', '>', 0)
                ->where('type', '=', 0)
                ->group('userid')
                ->select()
                ->toArray();

            $answer_count = count($answer_count);
            $unanswer_count = count($class_user_userid) - $answer_count;
            $value['answer_count'] = $answer_count;
            $value['unanswer_count'] = $unanswer_count;

            $list[$key] = $value;
        }

        View::assign('list', $list);

        //总测试人数人数， 合格人数
        $data = [];
        $count = count($class_user_userid);
        $test_count = Db::name('test_submit')->where('test_id', '=', $test_id)->where('type', '=', 0)->group('userid')->count();
        $pass_count = -1;

        if ($test['limits'] == 1) {
            $pass_count = Db::name('test_submit')
                ->where('resource_id', '=', $resource_id)
                ->where('test_id', '=', $test_id)
                ->where('score', '>=', $test['score'])
                ->where('type', '=', 0)
                ->group('userid')
                ->count();
        }
        $data['test_count'] = $test_count;
        $data['untest_count'] = $count - $test_count;

        $data['pass_count'] = $pass_count == -1 ? '未设置合格分数':$pass_count;
        $data['unpass_count'] = $pass_count == -1 ? '未设置合格分数':($test_count - $pass_count);

        View::assign('data', $data);
        View::assign('resource_id', $resource_id);
        View::assign('classes_id', $classes_id);

        return View::fetch();
    }


    // survey课件学习记录
    public function surveyLog(Request $request)
    {
        $resource_id = $request->get('resource_id');
        $classes_id = $request->get('classes_id');

        $courseware_id = Db::name('classes_step_resource')
            ->where('id', '=', $resource_id)
            ->value('courseware_id');

        $survey_id = Db::name('courseware_survey')
            ->where('courseware_id', '=', $courseware_id)
            ->value('id');

        View::assign('survey_id', $survey_id);

        View::assign('resource_id', $resource_id);
        View::assign('classes_id', $classes_id);
        return View::fetch();
    }

    public function getSurveyLogList(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        $get = $request->get();
        $where = [];

        if (isset($get['key'])) {
            if (!empty($get['key'])) {
                $where[] = ['b.name|b.userid', 'like', '%' . $get['key'] . '%'];
            }
        }

        $where[] = ['a.resource_id', '=', $get['resource_id']];
        $where[] = ['a.classes_id', '=', $get['classes_id']];

        $total = Db::table('o_classes_log')
            ->alias('a')
            ->join('o_members b', 'a.userid=b.userid', 'left')
            ->join('o_classes_step_resource c', 'c.id=a.resource_id', 'left')
            ->join('o_courseware d', 'd.id=c.courseware_id', 'left')
            ->join('o_courseware_survey e', 'e.courseware_id=d.id', 'left')
            ->where($where)
            ->count();

        $rows = Db::table('o_classes_log')
            ->alias('a')
            ->join('o_members b', 'a.userid=b.userid', 'left')
            ->join('o_classes_step_resource c', 'c.id=a.resource_id', 'left')
            ->join('o_courseware d', 'd.id=c.courseware_id', 'left')
            ->join('o_courseware_survey e', 'e.courseware_id=d.id', 'left')
            ->where($where)
            ->order('a.add_time', 'desc')
            ->field('a.id, d.title, a.classes_id, c.id as resource_id, d.id as courseware_id, a.name, b.department_name, b.division, a.userid, a.learning_time, e.id as survey_id')
            ->page($get['page'], $get['limit'])
            ->select()
            ->toArray();

        foreach ($rows as &$v) {

            $submit = Db::name('survey_submit')
                ->where('survey_id', '=', $v['survey_id'])
                ->where('class_id', '=', $get['classes_id'])
                ->where('type', '=', 1)
                ->where('userid', '=', $v['userid'])
                ->field('start_time, submit_time')
                ->find();

            if ($submit) {
                $v['start_time'] = $submit['start_time'] == '' ? '' : date('Y-m-d H:i:s',$submit['start_time']);
                $v['submit_time'] = $submit['submit_time'] == '' ? '' : date('Y-m-d H:i:s',$submit['submit_time']);
            } else {
                $v['start_time'] = '------';
                $v['submit_time'] = '------';
            }

            $count = mb_strlen($v['userid']);
            if ($count == 6) {
                if (is_numeric($v['userid'])) {
                    $v['userid'] = '00'.$v['userid'];
                }
            }
        }

        $data = array(
            'code'=> 0,
            'msg'=> '',
            'count' => $total,
            'data'=> $rows
        );
        return json($data);
    }


    //survey课件学习记录导出
    public function exportSurveyLog(Request $request)
    {

        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        ob_end_clean ();
        set_time_limit(0);
        //设置程序运行内存
        ini_set('memory_limit', '4096M');

        $fileName = '课件学习明细'.date('Ymd', time());
        header('Content-Encoding: UTF-8');
        header("Content-type:application/vnd.ms-excel;charset=UTF-8");
        header('Content-Disposition: attachment;filename="' . $fileName . '.csv"');


        //打开php标准输出流
        $fp = fopen('php://output', 'a');

        //添加BOM头，以UTF8编码导出CSV文件，如果文件头未添加BOM头，打开会出现乱码。
        fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));


        //添加导出标题
        fputcsv($fp, ['工号', '姓名', 'Division', '部门', '课件名称', '开始学习时间', '学习时长(s)', '提交时间']);


        $get = $request->get();
        $where = [];

        if (!empty($get['key'])) {
            $where[] = ['b.name|b.userid', 'like', '%' . $get['key'] . '%'];
        }

        $where[] = ['a.resource_id', '=', $get['resource_id']];
        $where[] = ['a.classes_id', '=', $get['classes_id']];

        $total = Db::table('o_classes_log')
            ->alias('a')
            ->join('o_members b', 'a.userid=b.userid', 'left')
            ->join('o_classes_step_resource c', 'c.id=a.resource_id', 'left')
            ->join('o_courseware d', 'd.id=c.courseware_id', 'left')
            ->join('o_courseware_survey e', 'e.courseware_id=d.id', 'left')
            ->where($where)
            ->count();

        $nums = 10; //每次导出数量
        $step = ceil($total/$nums); //循环次数

        for($i = 0; $i < $step; $i++) {
            $start = $i * $nums;
            $rows = Db::table('o_classes_log')
                ->alias('a')
                ->join('o_members b', 'a.userid=b.userid', 'left')
                ->join('o_classes_step_resource c', 'c.id=a.resource_id', 'left')
                ->join('o_courseware d', 'd.id=c.courseware_id', 'left')
                ->join('o_courseware_survey e', 'e.courseware_id=d.id', 'left')
                ->where($where)
                ->order('a.add_time', 'desc')
                ->field('a.id, d.title, a.classes_id, c.id as resource_id, d.id as courseware_id, a.name, b.department_name, b.division, a.userid, a.learning_time, e.id as survey_id')
                ->limit($start, $nums)
                ->select()
                ->toArray();

            foreach ($rows as &$v) {

                $submit = Db::name('survey_submit')
                    ->where('class_id', '=', $get['classes_id'])
                    ->where('survey_id', '=', $v['survey_id'])
                    ->where('type', '=', 1)
                    ->where('userid', '=', $v['userid'])
                    ->field('start_time, submit_time')
                    ->find();

                if ($submit) {
                    $start_time = $submit['start_time'] == '' ? '' : date('Y-m-d H:i:s',$submit['start_time']);
                    $submit_time = $submit['submit_time'] == '' ? '' : date('Y-m-d H:i:s',$submit['submit_time']);
                } else {
                    $start_time = '------';
                    $submit_time = '------';
                }

                $count = mb_strlen($v['userid']);
                if ($count == 6) {
                    if (is_numeric($v['userid'])) {
                        $userid = "'00".$v['userid'];
                    } else {
                        $userid = $v['userid'];
                    }
                } else {
                    $userid = $v['userid'];
                }

                $arr = [
                    $userid,
                    $v['name'],
                    $v['division'],
                    $v['department_name'],
                    $v['title'],
                    $start_time,
                    $v['learning_time'],
                    $submit_time
                ];

                fputcsv($fp, $arr);
            }

            flush();
        }


    }

    public function deleteSurveyLog(Request $request)
    {
        $id = $request->post('id');
        $survey_id = $request->post('survey_id');
        $classes_id= $request->post('classes_id');

        if (!$id) {
            return $this->outputAjax('参数不足！');
        }

        Db::startTrans();
        try {

            $userid = Db::name('classes_log')
                ->where('id', '=', $id)
                ->value('userid');

            $answer = Db::name('survey_answer')
                ->where('survey_id', '=', $survey_id)
                ->where('class_id', '=', $classes_id)
                ->where('userid', '=', $userid)
                ->where('test_type', '=', 1)
                ->select()
                ->toArray();

            if (empty($answer)) {
                return $this->outputAjax('删除失败所选学员未提交！');
            }

            $log = Db::name('classes_log')->where('id', '=', $id)->delete();
            if (!$log) {
                Db::rollback();
                return $this->outputAjax('删除失败[1]！');
            }


            $answer = Db::name('survey_answer')
                ->where('survey_id', '=', $survey_id)
                ->where('class_id', '=', $classes_id)
                ->where('userid', '=', $userid)
                ->where('test_type', '=', 1)
                ->delete();
            if (!$answer) {
                Db::rollback();
                return $this->outputAjax('删除失败[2]！');
            }

            $submit = Db::name('survey_submit')
                ->where('survey_id', '=', $survey_id)
                ->where('class_id', '=', $classes_id)
                ->where('userid', '=', $userid)
                ->where('type', '=', 1)
                ->delete();
            if (!$submit) {
                Db::rollback();
                return $this->outputAjax('删除失败[3]！');
            }

            Db::commit();
            return $this->outputAjax('删除成功！', 0);

        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }


    public function surveyAnalyze(Request $request)
    {
        $get = $request->get();

        $where = [];

        $where[] = ['id', '=', $get['resource_id']];
        $where[] = ['classes_id', '=', $get['classes_id']];

        $resource = Db::name('classes_step_resource')
            ->where($where)
            ->find();

        $survey = Db::name('courseware_survey')
            ->where('courseware_id', '=', $resource['courseware_id'])
            ->field('id, title')
            ->find();

        $subject = Db::name('courseware_survey_subject')
            ->where('survey_id', '=', $survey['id'])
            ->field('id, subject, other, subject_type')
            ->select()
            ->toArray();

        foreach ($subject as &$v) {
            if ($v['subject_type'] == 1) {
                $v['subject_type_name'] = '单选';

            } elseif ($v['subject_type'] == 2) {
                $v['subject_type_name'] = '多选';

            } elseif ($v['subject_type'] == 3) {
                $v['subject_type_name'] = '开放式';

            } else {
                $v['subject_type_name'] = '打分项';
            }

            $v['subject_id'] = $v['id'];
            $option = Db::name('courseware_survey_option')
                ->where('subject_id', '=', $v['id'])
                ->field('id as option_id, subject_id, title, letter')
                ->select()
                ->toArray();

            $v['options_count'] = count($option);

            if (!empty($v['other'])) {
                //+选择人数
                $count = Db::name('survey_answer')
                    ->where('survey_id', '=', $survey['id'])
                    ->where('class_id', '=', $get['classes_id'])
                    ->where('subject_id', '=', $v['id'])
                    ->where('type', '=', 2)
                    ->where('test_type', '=', 1)
                    ->count();
                $v['selected_count'] = $count;

                //+占比
                $count1 = Db::name('survey_answer')
                    ->where('survey_id', '=', $survey['id'])
                    ->where('class_id', '=', $get['classes_id'])
                    ->where('subject_id', '=', $v['id'])
                    ->where('test_type', '=', 1)
                    ->group('userid')
                    ->count();

                if ($count1 == 0) {
                    $v['percentage'] = '0%';
                } else {
                    $v['percentage'] = number_format(($count/$count1)*100, 1).'%';
                }

            } else {
                $v['selected_count'] = 0;
                $v['percentage'] = '0%';

            }

            $v['other_letter'] = $v['other'] != ''?$this->letter(count($option)):'';

            if ($v['subject_type'] == 3) {
                $answer = Db::name('survey_answer')
                    ->where('survey_id', '=', $survey['id'])
                    ->where('class_id', '=', $get['classes_id'])
                    ->where('subject_id', '=', $v['id'])
                    ->where('type', '=', 3)
                    ->where('test_type', '=', 1)
                    ->column('answer');
                $v['answer'] = implode("</<br>>", $answer);

            } else {
                $v['answer'] = '';
            }

            if ($v['subject_type'] == 1 || $v['subject_type'] == 2) {
                foreach ($option as &$val) {
                    //+选择人数
                    $count = Db::name('survey_answer')
                        ->where('survey_id', '=', $survey['id'])
                        ->where('class_id', '=', $get['classes_id'])
                        ->where('subject_id', '=', $val['subject_id'])
                        ->where('answer', '=', $val['option_id'])
                        ->where('type', '=', 1)
                        ->where('test_type', '=', 1)
                        ->count();
                    $val['selected_count'] = $count;

                    //+占比
                    $count1 = Db::name('survey_answer')
                        ->where('survey_id', '=', $survey['id'])
                        ->where('class_id', '=', $get['classes_id'])
                        ->where('subject_id', '=', $val['subject_id'])
                        ->where('test_type', '=', 1)
                        ->group('userid')
                        ->count();

                    if ($count1 == 0) {
                        $val['percentage'] = '0%';
                    } else {
                        $val['percentage'] = number_format(($count/$count1)*100, 1).'%';
                    }
                }
            } elseif ($v['subject_type'] == 4) {

                // 做题人数或计分人数
                $members_total = 0;
                // 总分
                $total_points = 0;

                foreach ($option as &$val) {

                    if ($val['letter'] != 'A') {
                        $members_count = Db::name('survey_answer')
                            ->where('survey_id', '=', $survey['id'])
                            ->where('class_id', '=', $get['classes_id'])
                            ->where('subject_id', '=', $val['subject_id'])
                            ->where('answer', '=', $val['option_id'])
                            ->where('type', '=', 4)
                            ->where('test_type', '=', 1)
                            ->count();
                        $members_total += $members_count;
                        $fraction = $this->fraction($val['letter']);
                        $total_points += $members_count*$fraction;
                    }

                    //+选择人数
                    $count = Db::name('survey_answer')
                        ->where('survey_id', '=', $survey['id'])
                        ->where('class_id', '=', $get['classes_id'])
                        ->where('subject_id', '=', $val['subject_id'])
                        ->where('answer', '=', $val['option_id'])
                        ->where('type', '=', 4)
                        ->where('test_type', '=', 1)
                        ->count();
                    $val['selected_count'] = $count;

                    //+占比
                    $count1 = Db::name('survey_answer')
                        ->where('survey_id', '=', $survey['id'])
                        ->where('class_id', '=', $get['classes_id'])
                        ->where('subject_id', '=', $val['subject_id'])
                        ->where('test_type', '=', 1)
                        ->group('userid')
                        ->count();

                    if ($count1 == 0) {
                        $val['percentage'] = '0%';
                    } else {
                        $val['percentage'] = number_format(($count/$count1)*100, 1).'%';
                    }
                }

                // 计分人数
                $v['scoring'] = $members_total;
                // 平均分
                $v['average'] = empty($total_points) ? 0 : number_format(($total_points/$members_total), 2);
            }


            $v['options'] = $option;
        }
        $survey['subject'] = $subject;

        $total = Db::name('survey_answer')
            ->where('class_id', '=', $get['classes_id'])
            ->where('survey_id', '=', $survey['id'])
            ->group('userid')
            ->count();
        View::assign('total', $total);
        View::assign('survey', $survey);

        View::assign('resource_id', $get['resource_id']);
        View::assign('classes_id', $get['classes_id']);
        return View::fetch();
    }

    protected function letter($key)
    {
        $data = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ','BA','BB','BC','BD','BE'];
        return $data[$key];
    }


    protected function fraction($key)
    {
        $data = ['B' => 1, 'C' => 2, 'D' => 3, 'E' => 4, 'F' => 5, 'G' => 6, 'H' => 7, 'I' => 8, 'J' => 9, 'K' => 10];
        return $data[$key];
    }


    //导出survey数据分析
    public function exportSurveyAnalysis(Request $request)
    {

        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $get = $request->get();


        ob_end_clean ();
        set_time_limit(0);
        //设置程序运行内存
        ini_set('memory_limit', '4096M');

        $fileName = 'Survey数据分析'.date('Ymd', time());
        header('Content-Encoding: UTF-8');
        header("Content-type:application/vnd.ms-excel;charset=UTF-8");
        header('Content-Disposition: attachment;filename="' . $fileName . '.csv"');


        //打开php标准输出流
        $fp = fopen('php://output', 'a');

        //添加BOM头，以UTF8编码导出CSV文件，如果文件头未添加BOM头，打开会出现乱码。
        fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));


        //添加导出标题
        fputcsv($fp, ['题目', '选项', '选择率', '人数', '平均值', '前端备注']);

        $where = [];

        $where[] = ['id', '=', $get['resource_id']];
        $where[] = ['classes_id', '=', $get['classes_id']];

        $resource = Db::name('classes_step_resource')
            ->where($where)
            ->find();

        $survey = Db::name('courseware_survey')
            ->where('courseware_id', '=', $resource['courseware_id'])
            ->field('id, title')
            ->find();

        $subject = Db::name('courseware_survey_subject')
            ->where('survey_id', '=', $survey['id'])
            ->field('id, subject, other, subject_type')
            ->select()
            ->toArray();

        $data = [];

        foreach ($subject as &$v) {
            if ($v['subject_type'] == 1) {
                $subject_type_name= '单选';

            } elseif ($v['subject_type'] == 2) {
                $subject_type_name = '多选';

            } elseif ($v['subject_type'] == 3) {
                $subject_type_name = '开放式';

            } else {
                $subject_type_name = '打分项';
            }

            if (!empty($v['other'])) {
                //+选择人数
                $count = Db::name('survey_answer')
                    ->where('survey_id', '=', $survey['id'])
                    ->where('subject_id', '=', $v['id'])
                    ->where('class_id', '=', $get['classes_id'])
                    ->where('type', '=', 2)
                    ->where('test_type', '=', 1)
                    ->count();
                //+占比
                $count1 = Db::name('survey_answer')
                    ->where('survey_id', '=', $survey['id'])
                    ->where('subject_id', '=', $v['id'])
                    ->where('class_id', '=', $get['classes_id'])
                    ->where('test_type', '=', 1)
                    ->group('userid')
                    ->count();
                $arr = [
                    'subject' => $v['subject'].'('.$subject_type_name.')',
                    'title' => $v['other'],
                    'percentage' => $count1 == 0 ? '0%' : number_format(($count/$count1)*100, 1).'%',
                    'selected_count' => $count,
                    'average' => '',
                    'remarks' => ''
                ];
                array_push($data, $arr);
            }

            if ($v['subject_type'] == 3) {
                $answer = Db::name('survey_answer')
                    ->where('survey_id', '=', $survey['id'])
                    ->where('subject_id', '=', $v['id'])
                    ->where('class_id', '=', $get['classes_id'])
                    ->where('type', '=', 3)
                    ->where('test_type', '=', 1)
                    ->column('answer');

                foreach ($answer as &$value) {
                    $arr = [
                        'subject' => $v['subject'].'('.$subject_type_name.')',
                        'title' => $value,
                        'percentage' => '',
                        'selected_count' => '',
                        'average' => '',
                        'remarks' => ''
                    ];
                    array_push($data, $arr);
                }
            }

            $option = Db::name('courseware_survey_option')
                ->where('subject_id', '=', $v['id'])
                ->field('id as option_id, subject_id, title, letter')
                ->select()
                ->toArray();

            if ($v['subject_type'] == 1 || $v['subject_type'] == 2) {
                foreach ($option as &$val) {
                    //+选择人数
                    $count = Db::name('survey_answer')
                        ->where('survey_id', '=', $survey['id'])
                        ->where('subject_id', '=', $val['subject_id'])
                        ->where('class_id', '=', $get['classes_id'])
                        ->where('answer', '=', $val['option_id'])
                        ->where('type', '=', 1)
                        ->where('test_type', '=', 1)
                        ->count();

                    //+占比
                    $count1 = Db::name('survey_answer')
                        ->where('survey_id', '=', $survey['id'])
                        ->where('subject_id', '=', $val['subject_id'])
                        ->where('class_id', '=', $get['classes_id'])
                        ->where('test_type', '=', 1)
                        ->group('userid')
                        ->count();

                    $arr = [
                        'subject' => $v['subject'].'('.$subject_type_name.')',
                        'title' => $val['title'],
                        'percentage' => $count1 == 0 ? '0%' : number_format(($count/$count1)*100, 1).'%',
                        'selected_count' => $count,
                        'average' => '',
                        'remarks' => ''
                    ];
                    array_push($data, $arr);
                }
            } elseif ($v['subject_type'] == 4) {
                $members_total = 0;
                $total_points = 0;
                $data1 = [];
                foreach ($option as &$val) {

                    if ($val['letter'] != 'A') {
                        $members_count = Db::name('survey_answer')
                            ->where('survey_id', '=', $survey['id'])
                            ->where('class_id', '=', $get['classes_id'])
                            ->where('subject_id', '=', $val['subject_id'])
                            ->where('answer', '=', $val['option_id'])
                            ->where('type', '=', 4)
                            ->where('test_type', '=', 1)
                            ->count();
                        $members_total += $members_count;
                        $fraction = $this->fraction($val['letter']);
                        $total_points += $members_count*$fraction;
                    }

                    //+选择人数
                    $count = Db::name('survey_answer')
                        ->where('survey_id', '=', $survey['id'])
                        ->where('subject_id', '=', $val['subject_id'])
                        ->where('class_id', '=', $get['classes_id'])
                        ->where('answer', '=', $val['option_id'])
                        ->where('type', '=', 4)
                        ->where('test_type', '=', 1)
                        ->count();

                    //+占比
                    $count1 = Db::name('survey_answer')
                        ->where('survey_id', '=', $survey['id'])
                        ->where('subject_id', '=', $val['subject_id'])
                        ->where('class_id', '=', $get['classes_id'])
                        ->where('test_type', '=', 1)
                        ->group('userid')
                        ->count();

                    $arr = [
                        'subject' => $v['subject'].'('.$subject_type_name.')',
                        'title' => $val['title'],
                        'percentage' => $count1 == 0 ? '0%' : number_format(($count/$count1)*100, 1).'%',
                        'selected_count' => $count,
                    ];
                    array_push($data1, $arr);
                }

                $remarks = Db::name('survey_answer')
                    ->where('survey_id', '=', $survey['id'])
                    ->where('class_id', '=', $get['classes_id'])
                    ->where('subject_id', '=', $v['id'])
                    ->where('type', '=', 4)
                    ->where('test_type', '=', 1)
                    ->column('remarks');

                foreach ($data1 as &$d) {
                    $arr = [
                        'subject' => $d['subject'],
                        'title' => $d['title'],
                        'percentage' => $d['percentage'],
                        'selected_count' => $d['selected_count'],
                    ];
                    $arr['average'] = empty($total_points) ? 0 : number_format(($total_points/$members_total), 2);
                    $arr['remarks'] = implode('|', $remarks);
                    array_push($data, $arr);
                }
            }

        }
        foreach ($data as &$v) {
            $arr = [
                $v['subject'],
                $v['title'],
                $v['percentage'],
                $v['selected_count'],
                $v['average'],
                $v['remarks']
            ];

            fputcsv($fp, $arr);
        }
        flush();
    }

    // 下载记录
    public function download(Request $request)
    {
        $classes_id = $request->get('classes_id');

        $data = Db::name('classes_step_resource')
            ->alias('a')
            ->join('o_courseware b', 'a.courseware_id=b.id','left')
            ->field('a.id, a.classes_id, b.title, b.id as courseware_id')
            ->where('a.classes_id', '=', $classes_id)
            ->where('b.type', '=', 2)
            ->select();

        View::assign('data', $data);
        View::assign('classes_id', $classes_id);
        return View::fetch();
    }

    // 下载记录加载
    public function getDownloadList(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        $get = $request->get();

        $where = [];

        if (isset($get['resource_id'])) {
            if (!empty($get['resource_id'])) {
                $where['a.resource_id'] = $get['resource_id'];
            }
        }


        $where['a.class_id'] = $get['classes_id'];

        $where['a.type'] = 1;

        $total = Db::table('o_download_log')
            ->alias('a')
            ->join('o_members b', 'a.userid=b.userid', 'left')
            ->where($where)
            ->count();

        $rows = Db::table('o_download_log')
            ->alias('a')
            ->join('o_members b', 'a.userid=b.userid', 'left')
            ->where($where)
            ->order('a.add_time', 'desc')
            ->field('a.id, a.name as resource_name, a.class_id, a.resource_id, b.name, b.department_name, b.division, a.userid, a.add_time')
            ->page($get['page'], $get['limit'])
            ->select()
            ->toArray();

        foreach ($rows as &$v) {
            $count = mb_strlen($v['userid']);
            if ($count == 6) {
                if (is_numeric($v['userid'])) {
                    $v['userid'] = '00'.$v['userid'];
                }
            }
        }
        $data = array(
            'code'=> 0,
            'msg'=> '',
            'count' => $total,
            'data'=> $rows
        );
        return json($data);
    }


    // 导出下载记录
    public function exportDownloadList(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $get = $request->get();

        $where = [];

        if (!empty($get['resource_id'])) {
            $where['a.resource_id'] = $get['resource_id'];
        }

        $where['a.class_id'] = $get['classes_id'];

        $where['a.type'] = 1;

        set_time_limit(0);
        //设置程序运行内存
        ini_set('memory_limit', '4096M');

        $fileName = '课件下载记录'.date('Ymd', time());
        header('Content-Encoding: UTF-8');
        header("Content-type:application/vnd.ms-excel;charset=UTF-8");
        header('Content-Disposition: attachment;filename="' . $fileName . '.csv"');


        //打开php标准输出流
        $fp = fopen('php://output', 'a');

        //添加BOM头，以UTF8编码导出CSV文件，如果文件头未添加BOM头，打开会出现乱码。
        fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));


        //添加导出标题
        fputcsv($fp, ['课件名称(CN)', 'Carol ID', '姓名', 'Division', '部门', '下载时间']);

        $total = Db::table('o_download_log')
            ->alias('a')
            ->join('o_members b', 'a.userid=b.userid', 'left')
            ->where($where)
            ->count();


        $nums = 2000; //每次导出数量
        $step = ceil($total/$nums); //循环次数

        for($i = 0; $i < $step; $i++) {
            $start = $i * $nums;

            $rows = Db::table('o_download_log')
                ->alias('a')
                ->join('o_members b', 'a.userid=b.userid', 'left')
                ->where($where)
                ->order('a.add_time', 'desc')
                ->field('a.id, a.name as resource_name, a.class_id, a.resource_id, b.name, b.department_name, b.division, a.userid, a.add_time')
                ->limit($start, $nums)
                ->select()
                ->toArray();

            foreach ($rows as $v) {
                $count = mb_strlen($v['userid']);
                if ($count == 6) {
                    if (is_numeric($v['userid'])) {
                        $userid = "'00".$v['userid'];
                    }
                }

                $arr = [
                    $v['resource_name'],
                    $userid,
                    $v['name'],
                    $v['division'],
                    $v['department_name'],
                    date('Y-m-d H:i',$v['add_time']),
                ];
                fputcsv($fp, $arr);
            }
            //每1千条数据就刷新缓冲区
            ob_flush();
            flush();
        }

    }



    // 课程评价
    public function evaluateLog(Request $request)
    {
        $classes_id = $request->get('classes_id');
        $is_review = $request->get('is_review');

        View::assign('classes_id', $classes_id);
        View::assign('is_review', $is_review);
        return View::fetch();
    }


    public function getEvaluateLogList(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        $get = $request->get();
        $where = [];

        if (isset($get['key'])) {
            if (!empty($get['key'])) {
                $where[] = ['b.name|b.userid', 'like', '%' . $get['key'] . '%'];
            }
        }

        $where[] = ['a.aid', '=', $get['classes_id']];
        $where[] = ['a.is_review', '=', $get['is_review']];
        $where[] = ['a.type', '=', 1];

        $total = Db::table('o_subject_submit')
            ->alias('a')
            ->join('o_members b', 'a.userid=b.userid', 'left')
            ->where($where)
            ->count();

        $rows = Db::table('o_subject_submit')
            ->alias('a')
            ->join('o_members b', 'a.userid=b.userid', 'left')
            ->where($where)
            ->order('a.id', 'desc')
            ->field('a.id, a.aid as classes_id, a.start_time, a.submit_time, b.department_name, b.division, b.name, a.userid')
            ->page($get['page'], $get['limit'])
            ->select()
            ->toArray();

        foreach ($rows as &$v) {

            $start_time = $v['start_time'];
            $submit_time = $v['submit_time'];

            $v['start_time'] = date('Y-m-d H:i:s', $v['start_time']);
            $v['submit_time'] = date('Y-m-d H:i:s', $v['submit_time']);
            $v['learning_time'] = $submit_time - $start_time;

            $count = mb_strlen($v['userid']);
            if ($count == 6) {
                if (is_numeric($v['userid'])) {
                    $v['userid'] = '00'.$v['userid'];
                }
            }
        }

        $data = array(
            'code'=> 0,
            'msg'=> '',
            'count' => $total,
            'data'=> $rows
        );
        return json($data);
    }


    //+ 课程评价导出
    public function exportEvaluateLog(Request $request)
    {

        if (!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        ob_end_clean();
        set_time_limit(0);
        //设置程序运行内存
        ini_set('memory_limit', '4096M');

        $fileName = '课程评价明细' . date('Ymd', time());
        header('Content-Encoding: UTF-8');
        header("Content-type:application/vnd.ms-excel;charset=UTF-8");
        header('Content-Disposition: attachment;filename="' . $fileName . '.csv"');


        //打开php标准输出流
        $fp = fopen('php://output', 'a');

        //添加BOM头，以UTF8编码导出CSV文件，如果文件头未添加BOM头，打开会出现乱码。
        fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));


        //添加导出标题
        fputcsv($fp, ['工号', '姓名', 'Division', '部门', '开始学习时间', '学习时长(s)', '提交时间']);


        $get = $request->get();
        $where = [];

        if (!empty($get['key'])) {
            $where[] = ['b.name|b.userid', 'like', '%' . $get['key'] . '%'];
        }

        $where[] = ['a.aid', '=', $get['classes_id']];
        $where[] = ['a.is_review', '=', $get['is_review']];
        $where[] = ['a.type', '=', 1];

        $total = Db::table('o_subject_submit')
            ->alias('a')
            ->join('o_members b', 'a.userid=b.userid', 'left')
            ->where($where)
            ->count();

        $nums = 10; //每次导出数量
        $step = ceil($total/$nums); //循环次数

        for($i = 0; $i < $step; $i++) {
            $start = $i * $nums;

            $rows = Db::table('o_subject_submit')
                ->alias('a')
                ->join('o_members b', 'a.userid=b.userid', 'left')
                ->where($where)
                ->order('a.id', 'desc')
                ->field('a.id, a.aid as classes_id, a.start_time, a.submit_time, b.department_name, b.division, b.name, a.userid')
                ->limit($start, $nums)
                ->select()
                ->toArray();

            foreach ($rows as &$v) {

                $start_time = date('Y-m-d H:i:s', $v['start_time']);
                $submit_time = date('Y-m-d H:i:s', $v['submit_time']);
                $learning_time = $v['submit_time'] - $v['start_time'];

                $count = mb_strlen($v['userid']);
                if ($count == 6) {
                    if (is_numeric($v['userid'])) {
                        $userid = "'00".$v['userid'];
                    } else {
                        $userid = $v['userid'];
                    }
                } else {
                    $userid = $v['userid'];
                }

                $arr = [
                    $userid,
                    $v['name'],
                    $v['division'],
                    $v['department_name'],
                    $start_time,
                    $learning_time,
                    $submit_time
                ];

                fputcsv($fp, $arr);
            }
            flush();
        }
    }


    //+ 删除课程评价
    public function deleteEvaluateLog(Request $request)
    {
        $id = $request->post('id');
        $classes_id = $request->post('classes_id');
        $is_review = $request->post('is_review');

        if (!$id) {
            return $this->outputAjax('参数不足！');
        }

        Db::startTrans();
        try {

            $inf = Db::name('subject_submit')
                ->where('id', '=', $id)
                ->find();


            $answer = Db::name('subject_answer')
                ->where('aid', '=', $classes_id)
                ->where('userid', '=', $inf['userid'])
                ->where('test_type', '=', 1)
                ->where('is_review', '=', $is_review)
                ->delete();
            if (!$answer) {
                Db::rollback();
                return $this->outputAjax('删除失败[2]！');
            }

            $submit = Db::name('subject_submit')
                ->where('id', '=', $id)
                ->delete();
            if (!$submit) {
                Db::rollback();
                return $this->outputAjax('删除失败[3]！');
            }

            Db::commit();
            return $this->outputAjax('删除成功！', 0);

        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }



    public function evaluateAnalyze(Request $request)
    {
        $get = $request->get();

        if ($get['is_review'] == 1) {
            $subject = Db::name('subject')
                ->where('id', 'in', '8,9,10,11,12,13')
                ->field('id, subject, subject_type')
                ->select()
                ->toArray();
        } else {
            $subject = Db::name('subject')
                ->where('id', 'in', '3,4,5,6,7')
                ->field('id, subject, subject_type')
                ->select()
                ->toArray();
        }


        // 做题人数或计分人数
        $members_total = 0;
        // 总分
        $total_points = 0;

        foreach ($subject as &$v) {
            if ($v['subject_type'] == 3) {
                $v['subject_type_name'] = '开放式';

            } else {
                $v['subject_type_name'] = '打分项';
            }

            $v['subject_id'] = $v['id'];
            $option = Db::name('subject_option')
                ->where('subject_id', '=', $v['id'])
                ->field('id as option_id, subject_id, title, letter')
                ->select()
                ->toArray();

            $v['options_count'] = count($option);

            if ($v['subject_type'] == 3) {
                $answer = Db::name('subject_answer')
                    ->where('aid', '=', $get['classes_id'])
                    ->where('subject_id', '=', $v['id'])
                    ->where('type', '=', 3)
                    ->where('test_type', '=', 1)
                    ->where('is_review', '=', $get['is_review'])
                    ->column('answer');
                $v['answer'] = implode("</<br>>", $answer);

            } else {
                $v['answer'] = '';
            }

            if ($v['subject_type'] == 4) {

                foreach ($option as &$val) {
                    if ($get['is_review'] == 1) {
                        if ($v['id'] == 13) {
                            if ($val['letter'] != 'A') {
                                $members_count = Db::name('subject_answer')
                                    ->where('aid', '=', $get['classes_id'])
                                    ->where('subject_id', '=', $val['subject_id'])
                                    ->where('answer', '=', $val['option_id'])
                                    ->where('type', '=', 4)
                                    ->where('test_type', '=', 1)
                                    ->where('is_review', '=', $get['is_review'])
                                    ->count();
                                $members_total += $members_count;
                                $fraction = $this->fraction($val['letter']);
                                $total_points += $members_count*$fraction;
                            }
                        }
                    } else {
                        if ($v['id'] == 6) {
                            if ($val['letter'] != 'A') {
                                $members_count = Db::name('subject_answer')
                                    ->where('aid', '=', $get['classes_id'])
                                    ->where('subject_id', '=', $val['subject_id'])
                                    ->where('answer', '=', $val['option_id'])
                                    ->where('type', '=', 4)
                                    ->where('test_type', '=', 1)
                                    ->where('is_review', '=', $get['is_review'])
                                    ->count();
                                $members_total += $members_count;
                                $fraction = $this->fraction($val['letter']);
                                $total_points += $members_count*$fraction;
                            }
                        }
                    }



                    //+选择人数
                    $count = Db::name('subject_answer')
                        ->where('aid', '=', $get['classes_id'])
                        ->where('subject_id', '=', $val['subject_id'])
                        ->where('answer', '=', $val['option_id'])
                        ->where('type', '=', 4)
                        ->where('test_type', '=', 1)
                        ->where('is_review', '=', $get['is_review'])
                        ->count();
                    $val['selected_count'] = $count;

                    //+占比
                    $count1 = Db::name('subject_answer')
                        ->where('aid', '=', $get['classes_id'])
                        ->where('subject_id', '=', $val['subject_id'])
                        ->where('test_type', '=', 1)
                        ->where('is_review', '=', $get['is_review'])
                        ->group('userid')
                        ->count();

                    if ($count1 == 0) {
                        $val['percentage'] = '0%';
                    } else {
                        $val['percentage'] = number_format(($count/$count1)*100, 1).'%';
                    }
                }
            }


            $v['options'] = $option;
        }
        // 平均分
        $average = empty($total_points) ? 0 : number_format(($total_points/$members_total), 2);

        $total = Db::name('subject_answer')
            ->where('aid', '=', $get['classes_id'])
            ->where('is_review', '=', $get['is_review'])
            ->group('userid')
            ->count();
        View::assign('total', $total);
        View::assign('subject', $subject);
        View::assign('average', $average);

        View::assign('classes_id', $get['classes_id']);
        View::assign('is_review', $get['is_review']);
        return View::fetch();
    }


    //导出课程评价数据分析
    public function exportEvaluateAnalysis(Request $request)
    {

        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $get = $request->get();


        ob_end_clean ();
        set_time_limit(0);
        //设置程序运行内存
        ini_set('memory_limit', '4096M');

        $fileName = '课程评价数据分析'.date('Ymd', time());
        header('Content-Encoding: UTF-8');
        header("Content-type:application/vnd.ms-excel;charset=UTF-8");
        header('Content-Disposition: attachment;filename="' . $fileName . '.csv"');


        //打开php标准输出流
        $fp = fopen('php://output', 'a');

        //添加BOM头，以UTF8编码导出CSV文件，如果文件头未添加BOM头，打开会出现乱码。
        fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));


        //添加导出标题
        fputcsv($fp, ['题目', '选项', '选择率', '人数', '平均值', '前端备注']);


        if ($get['is_review'] == 1) {
            $subject = Db::name('subject')
                ->where('id', 'in', '8,9,10,11,12,13')
                ->field('id, subject, subject_type')
                ->select()
                ->toArray();
        } else {
            $subject = Db::name('subject')
                ->where('id', 'in', '3,4,5,6,7')
                ->field('id, subject, subject_type')
                ->select()
                ->toArray();
        }

        $data = [];
        $members_total = 0;
        $total_points = 0;

        foreach ($subject as &$v) {
            if ($v['subject_type'] == 3) {
                $subject_type_name = '开放式';

            } else {
                $subject_type_name = '打分项';
            }


            if ($v['subject_type'] == 3) {
                $answer = Db::name('subject_answer')
                    ->where('subject_id', '=', $v['id'])
                    ->where('aid', '=', $get['classes_id'])
                    ->where('type', '=', 3)
                    ->where('test_type', '=', 1)
                    ->where('is_review', '=', $get['is_review'])
                    ->column('answer');

                foreach ($answer as &$value) {
                    $arr = [
                        'subject' => $v['subject'].'('.$subject_type_name.')',
                        'title' => $value,
                        'percentage' => '',
                        'selected_count' => '',
                        'average' => '',
                        'remarks' => ''
                    ];
                    array_push($data, $arr);
                }
            }

            $option = Db::name('subject_option')
                ->where('subject_id', '=', $v['id'])
                ->field('id as option_id, subject_id, title, letter')
                ->select()
                ->toArray();

            if ($v['subject_type'] == 4) {
                $data1 = [];
                foreach ($option as &$val) {

                    if ($get['is_review'] == 1) {
                        if ($v['id'] == 13) {
                            if ($val['letter'] != 'A') {
                                $members_count = Db::name('subject_answer')
                                    ->where('aid', '=', $get['classes_id'])
                                    ->where('subject_id', '=', $val['subject_id'])
                                    ->where('answer', '=', $val['option_id'])
                                    ->where('type', '=', 4)
                                    ->where('test_type', '=', 1)
                                    ->where('is_review', '=', $get['is_review'])
                                    ->count();
                                $members_total += $members_count;
                                $fraction = $this->fraction($val['letter']);
                                $total_points += $members_count*$fraction;
                            }
                        }
                    } else {
                        if ($v['id'] == 6) {
                            if ($val['letter'] != 'A') {
                                $members_count = Db::name('subject_answer')
                                    ->where('aid', '=', $get['classes_id'])
                                    ->where('subject_id', '=', $val['subject_id'])
                                    ->where('answer', '=', $val['option_id'])
                                    ->where('type', '=', 4)
                                    ->where('test_type', '=', 1)
                                    ->where('is_review', '=', $get['is_review'])
                                    ->count();
                                $members_total += $members_count;
                                $fraction = $this->fraction($val['letter']);
                                $total_points += $members_count*$fraction;
                            }
                        }
                    }


                    //+选择人数
                    $count = Db::name('subject_answer')
                        ->where('subject_id', '=', $val['subject_id'])
                        ->where('aid', '=', $get['classes_id'])
                        ->where('answer', '=', $val['option_id'])
                        ->where('type', '=', 4)
                        ->where('test_type', '=', 1)
                        ->where('is_review', '=', $get['is_review'])
                        ->count();

                    //+占比
                    $count1 = Db::name('subject_answer')
                        ->where('subject_id', '=', $val['subject_id'])
                        ->where('aid', '=', $get['classes_id'])
                        ->where('test_type', '=', 1)
                        ->where('is_review', '=', $get['is_review'])
                        ->group('userid')
                        ->count();

                    $arr = [
                        'subject' => $v['subject'].'('.$subject_type_name.')',
                        'title' => $val['title'],
                        'percentage' => $count1 == 0 ? '0%' : number_format(($count/$count1)*100, 1).'%',
                        'selected_count' => $count,
                    ];
                    array_push($data1, $arr);
                }

                $remarks = Db::name('subject_answer')
                    ->where('aid', '=', $get['classes_id'])
                    ->where('subject_id', '=', $v['id'])
                    ->where('type', '=', 4)
                    ->where('test_type', '=', 1)
                    ->where('is_review', '=', $get['is_review'])
                    ->column('remarks');

                foreach ($data1 as &$d) {
                    $arr = [
                        'subject' => $d['subject'],
                        'title' => $d['title'],
                        'percentage' => $d['percentage'],
                        'selected_count' => $d['selected_count'],
                    ];
                    $arr['remarks'] = implode('|', $remarks);
                    array_push($data, $arr);
                }
            }

        }
        $average = empty($total_points) ? 0 : number_format(($total_points/$members_total), 2);
        foreach ($data as &$v) {
            $arr = [
                $v['subject'],
                $v['title'],
                $v['percentage'],
                $v['selected_count'],
                $average,
                $v['remarks']
            ];

            fputcsv($fp, $arr);
        }
        flush();
    }

    //线下班级学习记录
    public function record()
    {
        return View::fetch();
    }


    public function getRecordList(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        $get = $request->get();
        $where = [];
        if (isset($get['tree_select_nodeId'])) {
            if (!empty($get['tree_select_nodeId'])) {
                $department = $get['tree_select_nodeId'];
                $arr = get_children($department, 1);
                $arr[] = $department;
                $department = implode('|', $arr);
                $where[]  = ['', 'EXP', Db::raw("CONCAT(',',e.department,',') REGEXP concat(',(',replace('".$department."',',','|'),'),')")];
            }
        }

        if (isset($get['key'])) {
            if (!empty($get['key'])) {
                $where[] = ['e.name|e.userid', 'like', '%' . $get['key'] . '%'];
            }
        }

        $where[] = ['e.status', '=', 1];


        if (isset($get['field']) && isset($get['order'])) {
            if ( !empty($get['field']) && !empty($get['order'])) {
                $field = $get['field'];
                $sort = $get['order'];
            } else {
                $field = 'duration';
                $sort = 'desc';
            }
        } else {
            $field = 'duration';
            $sort = 'desc';
        }
        $where1 = [];
        $where2 = [];
        $where3 = [];
        if (isset($get['time'])) {
            if (!empty($get['time'])) {
                $t = explode(' - ', $get['time']);
                $where1[] = ['a.add_time', 'between', [strtotime($t[0]), strtotime($t[1])+86399]];
                $where2[] = ['a.add_time', 'between', [strtotime($t[0]), strtotime($t[1])+86399]];
                $where3[] = ['a.add_time', 'between', [strtotime($t[0]), strtotime($t[1])+86399]];
            }
        }

        if (isset($get['source'])) {
            if (!empty($get['source'])) {
                $where3[] = ['a.source', '=', $get['source']];
            }
        }

        // 取得满足条件的记录数

        $subQuery1 = Db::table('o_classes_user')
            ->alias('a')
            ->join('o_members b','a.userid=b.userid','left')
            ->field('COUNT(a.classes_id) as classes_total, a.userid')
            ->where($where1)
            ->where('b.status', '=', 1)
            ->group('a.userid')
            ->buildSql();

        $subQuery2 = Db::table('o_classes_user')
            ->alias('a')
            ->join('o_classes b', 'b.id=a.classes_id','left')
            ->join('o_members c','a.userid=c.userid','left')
            ->where('b.end', '<', time())
            ->where('c.status', '=', 1)
            ->field('COUNT(a.classes_id) as end_total, a.userid')
            ->group('a.userid')
            ->where($where2)
            ->buildSql();

        $subQuery3 = Db::table('o_classes_log')
            ->alias('a')
            ->join('o_members b','a.userid=b.userid','left')
            ->field('SUM(a.learning_time) as duration, a.userid')
            ->where($where3)
            ->where('b.status', '=', 1)
            ->group('a.userid')
            ->buildSql();

        $total = Db::table('o_classes_user')
            ->alias('a')
            ->join($subQuery1.'b','a.userid=b.userid','left')
            ->join($subQuery2.'c','a.userid=c.userid','left')
            ->join($subQuery3.'d','a.userid=d.userid','left')
            ->join('o_members e','a.userid=e.userid','left')
            ->where($where)
            ->group('a.userid')
            ->count();

        // 分页查询数据
        $rows = Db::table('o_classes_user')
            ->alias('a')
            ->join($subQuery1.'b','a.userid=b.userid','left')
            ->join($subQuery2.'c','a.userid=c.userid','left')
            ->join($subQuery3.'d','a.userid=d.userid','left')
            ->join('o_members e','a.userid=e.userid','left')
            ->group('a.userid')
            ->where($where)
            ->order($field, $sort)
            ->page($get['page'], $get['limit'])
            ->field('e.name, e.userid, e.department_name, e.division, b.classes_total, c.end_total, d.duration')
            ->select()
            ->toArray();

        foreach ($rows as &$v) {

            if (empty($v['classes_total'])) {
                $v['classes_total'] = 0;
            }

            if (empty($v['duration'])) {
                $v['duration'] = 0;
            }

            if (empty($v['end_total'])) {
                $v['end_total'] = 0;
            }

            $class_id = Db::name('classes_user')
                ->where('userid', '=', $v['userid'])
                ->column('classes_id');

            foreach ($class_id as $key => $val) {

                $resource = Db::name('classes_step_resource')
                    ->where('classes_id', '=', $val)
                    ->count();
                $log = Db::name('classes_log')
                    ->where('classes_id', '=', $val)
                    ->where('is_finish', '=', 1)
                    ->where('userid', '=', $v['userid'])
                    ->where($where1)
                    ->group('resource_id')
                    ->count();
                if ($resource != $log) {
                    unset($class_id[$key]);
                }
            }
            $v['finished_total'] = count($class_id);
            $count = mb_strlen($v['userid']);
            if ($count == 6) {
                if (is_numeric($v['userid'])) {
                    $v['userid'] = '00'.$v['userid'];
                }
            }
        }

        $data = array(
            'code'=> 0,
            'msg'=> '',
            'count' => $total,
            'data'=> $rows
        );
        return json($data);
    }

    // 学习记录导出

    public function exportRecord(Request $request)
    {

        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $post = $request->post();

        $res = Db::name('document')
            ->where('type', '=', 'ClassesRecordJobQueue')
            ->where('url', '=', '')
            ->find();

        if ($res) {
            return $this->outputAjax('已有下载任务, 请勿重复操作');
        }

        Db::startTrans();
        try {

            if (!empty($post['tree_select_nodeId'])) {
                $department = $post['tree_select_nodeId'];
                $arr = get_children($department, 1);
                $arr[] = $department;
                $department = implode('|', $arr);
            } else {
                $department = '';
            }

            if (!empty($post['time'])) {
                $t = explode(' - ', $post['time']);
                $start = $t[0];
                $end = $t[1];
            } else {
                $start = '';
                $end = '';
            }

            if (!empty($post['key'])) {
                $key = $post['key'];
            } else {
                $key = '';
            }

            if (!empty($post['source'])) {
                $source = $post['source'];
            } else {
                $source = '';
            }


            $ts = time();

            $insert = array(
                'admin_id' => session('admin_auth.id'),
                'title' => '班级课程学习明细-'.date('YmdHis', $ts),
                'url' => '',
                'type' => 'ClassesRecordJobQueue',
                'add_time' => $ts
            );

            $download_id = Db::name('document')->insertGetId($insert);
            if (!$download_id) {
                Db::rollback();
                return $this->outputAjax('任务添加失败[2]');
            }

            // 1.当前任务由哪个类来负责处理
            // 当轮到该任务时，系统将生成该类的实例，并调用其fire方法
            $jobHandlerClassName = 'app\job\JobClassesTotal@task2';

            // 2.当任务归属的队列名称，如果为新队列，会自动创建
            $jobQueueName = "ClassesRecordJobQueue";


            // 3.当前任务所需业务数据，不能为resource类型，其他类型最终将转化为json形式的字符串
            $jobData = ['ts' => $ts, 'download_id' => $download_id, 'page' => 1, 'start' => $start, 'end' => $end, 'department' => $department, 'key' => $key, 'source' => $source];

            // 4.将该任务推送到消息列表，等待对应的消费者去执行
            // 入队列，later延迟执行，单位秒，push立即执行
            $isPushedTask2 = Queue::push($jobHandlerClassName, $jobData, $jobQueueName);

            // database 驱动时，返回值为 1|false  ;   redis 驱动时，返回值为 随机字符串|false
            if ($isPushedTask2 !== false) {

                Db::commit();
                return $this->outputAjax('任务添加成功, 稍后在下载中心查看', 0);

            } else {

                Db::rollback();
                return $this->outputAjax('任务添加失败');

            }
        } catch (\Exception $e) {

            Db::rollback();
            return $this->outputAjax($e->getMessage());

        }
    }
}